How do I implement a CString hash function for use with std::unordered_map?

后端 未结 2 1660

I want to declare :

std::unordered_map m_mapMyMap;

But when I build I got an error telling me that the standard C++

2条回答
  •  长情又很酷
    2020-12-11 19:36

    Based on the MS STL implementation for std::string I created the following methods which can be used for std::unordered_set and std::unordered_map:

    namespace std {
        template <>
        struct hash
        {   // hash functor for CString
            size_t operator()(const CString& _Keyval) const
            {   // hash _Keyval to size_t value by pseudorandomizing transform
                return (_Hash_seq((const unsigned char*)(LPCWSTR)_Keyval, _Keyval.GetLength() * sizeof(wchar_t)));
            }
        };
    
        template <>
        struct hash
        {   // hash functor for CStringA
            size_t operator()(const CStringA& _Keyval) const
            {   // hash _Keyval to size_t value by pseudorandomizing transform
                return (_Hash_seq((const unsigned char*)(LPCSTR)_Keyval, _Keyval.GetLength() * sizeof(char)));
            }
        };
    }
    

    Or even more generic:

    namespace std {
        template
        struct hash> : public unary_function, size_t>
        {   // hash functor for CStringT
            typedef CStringT _Kty;
    
            size_t operator()(const _Kty& _Keyval) const
            {   // hash _Keyval to size_t value by pseudorandomizing transform
                return (_Hash_seq((const unsigned char*)(StringTraits::PCXSTR)_Keyval,
                    _Keyval.GetLength() * sizeof(BaseType)));
            }
        };
    }
    

提交回复
热议问题