定义哈希函数和比较函数
#include <hash_map>
#include <string>
#include <iostream>
using namespace std;
//define the class
struct ClassA
{
ClassA(int a):c_a(a){}
int getvalue()const { return c_a;}
size_t c_a;
};
//1 define the hash function
struct hash_A
{
enum
{ // parameters for hash table
bucket_size =2 ,
min_buckets =4
};
size_t operator()(const class ClassA & A)const
{
return A.getvalue()%min_buckets;
}
//2 define the equal function
bool operator()(const class ClassA & a1, const class ClassA & a2)const
{
return a1.getvalue()<a2.getvalue();
}
};
int main()
{
hash_map<ClassA,string, hash_A> hmap;
ClassA a1(2);
hmap[a1]="I love C++";
ClassA a2(56);
hmap[a2]="Do you love it?";
cout<<hmap[a1]<<endl;
cout<<hmap[a2]<<endl;
return 0;
}
本文介绍了一个使用C++实现的哈希表应用实例,通过定义特定的哈希函数和比较函数来操作自定义类型的键值对。展示了如何为自定义类型创建哈希映射,并在哈希表中插入及检索数据。
715

被折叠的 条评论
为什么被折叠?



