【问题标题】:unorder_map<float, short> Why does this work?unordered_map<float, short> 为什么会这样?
【发布时间】:2011-12-07 04:30:12
【问题描述】:

我正在使用unordered_map&lt;float, unsigned short&gt; 在 C++ 中实现哈希表。

我知道在大多数情况下使用浮点数作为哈希表的键是一个的想法,因为比较它们很容易出错。但是,在这些情况下,我是从大文件中读取浮点数,并且它们的精度是已知且恒定的。

但是,我想知道unordered_map 如何散列我的浮点数以估计碰撞频率的详细信息。创建unordered_map 时,我没有覆盖默认哈希实现。根据文档,默认哈希函数是std::hash&lt;Key&gt;。在我的情况下是std::hash&lt;float&gt;。但是,当我查看std::hash 文档时,它仅针对“char*const char*cropewrope 和内置整数类型类型的模板参数”定义。

有谁知道在我将值添加到 unordered_map 时调用了什么函数来散列这些值?

unordered_map - http://msdn.microsoft.com/en-us/library/bb982522.aspx

std::hash - http://www.sgi.com/tech/stl/hash.html#1

【问题讨论】:

    标签: hash hashtable unordered-map


    【解决方案1】:

    根据 C++11 标准,std::hash 也支持float。实际的哈希函数取决于实现,因此即使您可以计算出当前编译器的冲突频率,较新的版本或不同的编译器也可能实现不同的哈希函数。以下是std::hash 专业化的完整列表:

    template <> struct hash<bool>;
    template <> struct hash<char>;
    template <> struct hash<signed char>;
    template <> struct hash<unsigned char>;
    template <> struct hash<char16_t>;
    template <> struct hash<char32_t>;
    template <> struct hash<wchar_t>;
    template <> struct hash<short>;
    template <> struct hash<unsigned short>;
    template <> struct hash<int>;
    template <> struct hash<unsigned int>;
    template <> struct hash<long>;
    template <> struct hash<unsigned long>;
    template <> struct hash<long long>;
    template <> struct hash<unsigned long long>;
    template <> struct hash<float>;
    template <> struct hash<double>;
    template <> struct hash<long double>;
    template <class T> struct hash<T*>;
    

    【讨论】:

    • @JHowIX:它在 C++11 之前存在
    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 2011-06-03
    • 2018-06-08
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多