【侯捷-SL体系结构内核分析-一个万用的 hash function】
我们知道,unordered_set / unordered_multiset / unordered_map / unordered_multimap 内部是用哈希表实现的,需要一个哈希函数来计算元素应该放在哪个 bucket 中。对于基本的数据类型,比如 int, float, double, string等,STL为我们提供了相应的哈希函数(仿函数),那对于我们自己定义的类类型呢?该如何定义它的哈希函数呢?比如下面有一个自己定义的类型 Custom,想把它放进 unordered_set 容器中:
struct Custom
{
string str_FirstName;
string str_LastName;
long l_ID;
};
这时候,我们就需要为Custom自己定义一个哈希函数。一个很自然的想法就是计算每一个基本类型的 hash 数值,然后再相加,就可以作为 Custom 类型的哈希函数,如下所示:
struct CustomHash
{
std::size_t operator()(const Custom& custom) const
{
return hash<string>()(custom.str_FirstName) +
hash<string>()(custom.str_LastName) +
hash<long>()(custom.l_ID);
}
};
这其实是一种不明智的做法。有一个比较万能的 hash function,代码如下:
//计算种子数值
template<typename T>
inline void hash_combine(size_t& seed, const T& val)
{
seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) +