我需要为 unordered_map
专门化哈希函数,这样我就可以使用 int 数组作为键。数组值通常为 0 或 1,例如int array = {0, 1, 0, 1}
,但技术上没有限制。
在这种情况下,有人可以推荐一个好的哈希函数吗?或者,我总是可以将 int 数组转换为字符串并避免特化。但我担心性能,因为我可能有数百万个这样的数组。
最佳答案
C++ TR1 包含一个散列模板函数。
如果您还没有,可以使用 Boost Hash。
一个方便的助手的想法:
#include <boost/functional/hash.hpp>
template <typename T, int N>
static std::size_t hasharray(const T (&arr)[N])
{
return boost::hash_range(arr, arr+N);
}
这将(大致?)等同于
size_t seed = 0;
for (const T* it=arr; it!=(arr+N); ++it)
boost::hash_combine(seed, *it);
return seed;
如果您使用此哈希进行查找,请不要忘记实现适当的相等比较操作
关于用于 int 数组的 C++ 哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7148624/