用于unordered_map中字符串的C ++哈希函数

时间:2013-03-24 06:25:59

标签: c++ string c++11 key unordered-map

似乎C ++没有标准库中字符串的哈希函数。这是真的吗?

在unordered_map中使用字符串作为键可以使用任何c ++编译器的工作示例是什么?

5 个答案:

答案 0 :(得分:27)

C ++ STL为各种字符串类提供std::hash的模板specializations。您只需指定std::string作为std::unordered_map的关键字类型:

#include <string>
#include <unordered_map>

int main()
{
    std::unordered_map<std::string, int> map;
    map["string"] = 10;
    return 0;
}

答案 1 :(得分:18)

我今天遇到了这个问题(实际上是wstring,而不是string,但这是相同的交易):使用wstring作为unordered_map中的密钥会产生错误关于没有可用于该类型的哈希函数。

我的解决方案是添加:

#include <string>

信不信由你,如果没有包含,我仍然可以使用wstring类型,但显然不是哈希这样的辅助功能。只需添加上面的包含修复它。

答案 2 :(得分:13)

实际上,有std::hash<std::string>

但是你可以使用另一个哈希函数:

struct StringHasher {
    size_t operator()(const std::string& t) const {
          //calculate hash here.
    }
}

unordered_map<std::string, ValueType, StringHasher>

答案 3 :(得分:7)

如果你有一个CustomType,并且想要插入STL基础设施,这就是你可以做的。

namespace std
{
//namespace tr1
//{
    // Specializations for unordered containers

    template <>
    struct hash<CustomType> : public unary_function<CustomType, size_t>
    {
        size_t operator()(const CustomType& value) const
        {
            return 0;
        }
    };

//} // namespace tr1

template <>
struct equal_to<CustomType> : public unary_function<CustomType, bool>
{
    bool operator()(const CustomType& x, const CustomType& y) const
    {
        return false;
    }
};

} // namespace std

如果您想创建说std::unordered_map<CustomType>,则STL会找到hashequal_to函数,而无需您对模板执行任何其他操作。这就是我喜欢编写支持无序数据结构的自定义相等比较器的方法。

答案 4 :(得分:0)

就我而言,这真的让人分心。

我有一个X型,我为 const&amp; X 在某处

使用它
std::unordered_map<const X, int> m_map;

然后我想要另一张地图,其中哪个键的类型为X并且确实:

std::unordered_map<X, int> map_x;

请注意第二种情况下const LACK

相关问题