C++11构造unordered_map时,key和value的数据类型有哪些限制?
我尝试创建这个:
unordered_map<vector<int>, int>
这给了我一个编译错误。我需要编写自己的哈希器吗?
最佳答案
std::unordered_map
的键需要通过专门化 std::hash
进行哈希实现.
STL 中定义的基本类型的标准特化是:
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*>;
对于其他一切,您需要编写自己的哈希值和/或使用 boost::hash
.
此外,如Tony D的评论说:
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.
关于c++ - unordered_map 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26176293/