What kind of restrictions are there on the datatype of key and value when constructing an unordered_map in C++11?
I tried to create this:
unordered_map<vector<int>, int>
This gave me a compilation error. Do I need to write my own hasher?
What kind of restrictions are there on the datatype of key and value when constructing an unordered_map in C++11?
I tried to create this:
unordered_map<vector<int>, int>
This gave me a compilation error. Do I need to write my own hasher?
std::unordered_map
's keys need a hash implementation by specialising std::hash
.
The standard specializations for basic types which are defined in the STL are:
template<> struct hash<bool>;
template<> struct hash<char>;
template<> struct hash<signed char>;
template<> struct hash<unsigned char>;
template<> struct hash<char16_t>;
template<> struct hash<char32_t>;
template<> struct hash<wchar_t>;
template<> struct hash<short>;
template<> struct hash<unsigned short>;
template<> struct hash<int>;
template<> struct hash<unsigned int>;
template<> struct hash<long>;
template<> struct hash<long long>;
template<> struct hash<unsigned long>;
template<> struct hash<unsigned long long>;
template<> struct hash<float>;
template<> struct hash<double>;
template<> struct hash<long double>;
template< class T > struct hash<T*>;
For everything else you need to write your own hash and/or use boost::hash
.
Furthermore as Tony D's comment says:
You can specify the hash function as a third template parameter if you prefer. Separately, operator== must also be available for the key objects, or comparison specified as a fourth template parameter.