c++ - 为什么 C++ POD 结构没有默认散列?

标签 c++ templates hash struct unordered-map

我想使用 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/

相关文章:

c++ - 根据模板变量类型执行不同的方法

c++ - 是否有良好/广泛采用的 c++ 模板编码约定/标准?

php - 如何将登录脚本中的安全性从 MD5 更新为更安全的内容?

node.js - Redis 在哈希列表中按喜欢排序?

c++ - 来自并发 HashMap 的迭代器是否安全?

C++ 模板友元类

c++ - 我有多个通过 StackView 推送的 qml 文件。我如何将它们连接到 C++

c++ - 通过分发目标文件加速编译

c++ - C++中的模板函数重载

ruby-on-rails - Rails:使用 Decoder::Countries[:US].states 使用美国各州和缩写填充选择列表