Hash for a std::pair, for use in an unordered_map

Hash for a std::pair, for use in an unordered_map

本文关键字:for unordered an map in std pair Hash use      更新时间:2023-10-16

当做

unordered_map<pair<unsigned int, unsigned int>, unsigned int> m;

我们得到

错误 C2338:C++标准不为此类型提供哈希。

是否有一种内置方法来定义intstd::pair哈希,或者我们需要手动定义它?(在这种情况下,哈希可能只是(第一项的字节((对中第二项的字节(粘在一起(。

注意:我使用的是VC++ 2013。

注意2:pair<int,int>pair作为unordered_map问题的键的答案并没有清楚地解决如何实际创建具有两个int哈希的问题,详见此处。

如果你不想使用boost,那么滚动你自己的不应该太难。 添加static_assert以确保保持 2 个整数适合 1 个size_t的假设。

using IntPair = std::pair<int, int>;
struct IntPairHash {
static_assert(sizeof(int) * 2 == sizeof(size_t));
size_t operator()(IntPair p) const noexcept {
return size_t(p.first) << 32 | p.second;
}
};
std::unordered_map<IntPair, int, IntPairHash> myMap;