代码之家  ›  专栏  ›  技术社区  ›  MirroredFate

无序映射中字符串的C++哈希函数

  •  44
  • MirroredFate  · 技术社区  · 13 年前

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

    在一个可以与任何c++编译器一起使用的无序映射中,使用字符串作为键的工作示例是什么?

    5 回复  |  直到 13 年前
        1
  •  36
  •   awesoon    10 年前

    C++STL提供模板 specializations 属于 std::hash 用于各种字符串类。你可以指定 std::string 作为的密钥类型 std::unordered_map :

    #include <string>
    #include <unordered_map>
    
    int main()
    {
        std::unordered_map<std::string, int> map;
        map["string"] = 10;
        return 0;
    }
    
        2
  •  23
  •   Ardent Coder Michael Richardson    6 年前

    我今天遇到了这个(实际上是和 wstring string ,但这是相同的交易):使用 wstring(字符串) 作为 unordered_map 生成一个关于没有可用于该类型的哈希函数的错误。

    我的解决方案是添加:

    #include <string>
    

    信不信由你,没有 #include 指令我还有 wstring(字符串) 类型可用,但显然没有散列之类的辅助函数。只需在上面添加include就可以修复它。

        3
  •  17
  •   RiaD    13 年前

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

    但在这里,您可以使用另一个哈希函数:

    struct StringHasher {
        size_t operator()(const std::string& t) const {
              //calculate hash here.
        }
    }
    
    unordered_map<std::string, ValueType, StringHasher>
    
        4
  •  8
  •   John Leidegren    13 年前

    如果你有 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将找到 hash equal_to 函数,而无需对模板执行任何其他操作。这就是我喜欢编写自定义相等比较器的方式,它支持无序的数据结构。

        5
  •  0
  •   sergiol    9 年前

    就我而言,这真的很分散注意力。

    我有一个类型X,我为它实现了哈希 常量&十、 在某个地方与

    std::unordered_map<const X, int> m_map;
    

    然后我想要另一张地图,哪把钥匙是那种类型的 X 并且做到了:

    std::unordered_map<X, int> map_x;
    

    请注意 缺乏 属于 const 关于第二种情况。

    推荐文章