前几天同事提起C++没有hash_map,听到我就笑了:这位同事的知识该有多久没有更新了呀!于是决定网上找个C++ unordered_map使用示例给他,发现百度出来的结果有些作者自己都说无法编译通过,有的示例我亲测无法编译通过的。于是决定按照最朴素的用法给他写了个示例,源码如下:
#include<string>
#include<iostream>
#include<unordered_map>
using namespace std;
class search_key_t{
public:
search_key_t(long long most_significant_64, int least_significant_32):
ms64(most_significant_64), ls32(least_significant_32)
{
}
bool operator==(const search_key_t &sk) const
{
return ms64 == sk.ms64 && ls32 == sk.ls32;
}
long long ms64;
int ls32;
};
struct search_key_hasher{
size_t operator()(const search_key_t &p) const
{
size_t hash = p.ls32;
hash ^= (p.ms64 >> 32);
hash ^= (int)p.ms64;
return hash;
}
};
int main()
{
typedef std::unordered_map<search_key_t, int, search_key_hasher> hash_map;
hash_map hm;
for(int i = 0; i < 10; ++i)
{
search_key_t k(i, i);
hm[k] = i;
}
for(hash_map::iterator iter = hm.begin(); iter != hm.end(); iter++)
{
const search_key_t &k = iter->first;
cout << "k.ms64=" << k.ms64 << ", k.ls32=" << k.ls32 << ", val=" << iter->second << endl;
}
return 0;
}
上述是所有代码,其实unordered_map使用自定义类型作为key时,主要需要做两件事:
1. 为key类型提供一个equal运算符,
2. 提供一个hash函数。
本人使用gcc-4.8.5编译器,亲测是这样的(这里本人提供的hash函数没有进行任何考量,请按照自己需求进行改动):[heron@heron.chogori server_routines]# g++ tom.cc -std=gnu++11
[heron@heron.chogori server_routines]# ./a.out
k.ms64=9, k.ls32=9, val=9
k.ms64=8, k.ls32=8, val=8
k.ms64=7, k.ls32=7, val=7
k.ms64=6, k.ls32=6, val=6
k.ms64=5, k.ls32=5, val=5
k.ms64=4, k.ls32=4, val=4
k.ms64=3, k.ls32=3, val=3
k.ms64=2, k.ls32=2, val=2
k.ms64=1, k.ls32=1, val=1
k.ms64=0, k.ls32=0, val=0
[heron@heron.chogori server_routines]#