我想使用 POD 结构作为映射中的哈希键,例如
struct A { int x; int y; };
std::unordered_map<A, int> my_map;
但我不能这样做,因为没有哈希函数可以为此类结构自动生成。
- 为什么 C++ 标准不需要 POD 结构的默认散列?
- 为什么编译器(特别是 GCC 4.x/5.x)提供这样的哈希,即使标准没有强制要求?
- 如何使用模板以可移植的方式为我的所有 POD 结构生成哈希函数(如有必要,我愿意做出语义假设)?
最佳答案
来自 documentation ,在您的情况下可能的实现方式是:
#include<functional>
#include<unordered_map>
struct A { int x; int y; };
namespace std
{
template<> struct hash<A>
{
using argument_type = A;
using result_type = std::size_t;
result_type operator()(argument_type const& a) const
{
result_type const h1 ( std::hash<int>()(a.x) );
result_type const h2 ( std::hash<int>()(a.y) );
return h1 ^ (h2 << 1);
}
};
}
int main() {
std::unordered_map<A, int> my_map;
}
我们不允许编译器生成这样的特化,因为标准没有定义类似的东西(正如评论中已经提到的那样)。
关于c++ - 为什么 C++ POD 结构没有默认散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826416/