C++ Hash function for string in unordered_map

前端 未结 5 1599
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 00:46

It seems as if C++ does not have a hash function for strings in the standard library. Is this true?

What is a working example of using a string as a key in an unordered_

5条回答
  •  庸人自扰
    2021-02-05 01:20

    If you have a CustomType and you want to plug into the STL infrastructure this is what you could do.

    namespace std
    {
    //namespace tr1
    //{
        // Specializations for unordered containers
    
        template <>
        struct hash : public unary_function
        {
            size_t operator()(const CustomType& value) const
            {
                return 0;
            }
        };
    
    //} // namespace tr1
    
    template <>
    struct equal_to : public unary_function
    {
        bool operator()(const CustomType& x, const CustomType& y) const
        {
            return false;
        }
    };
    
    } // namespace std
    

    If you then want to create say a std::unordered_map the STL will find the hash and equal_to functions without you having to do anything more with the template. This is how I like to write my custom equality comparer that support unordered data structures.

提交回复
热议问题