C++ Hash function for string in unordered_map

MirroredFate picture MirroredFate · Mar 24, 2013 · Viewed 61.4k times · Source

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_map that will work with any c++ compiler?

Answer

awesoon picture awesoon · Mar 24, 2013

C++ STL provides template specializations of std::hash for the various string classes. You could just specify std::string as key type for std::unordered_map:

#include <string>
#include <unordered_map>

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