c++ - unordered_map 的键

标签 c++ c++11 unordered-map

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/

相关文章:

c++ - 在 DDD 中隐藏静态数据成员,或者只显示某些成员

c++ - Hexfloat 机械手和精度

c++ - unordered_map emplace 编译错误

c++ - 如何将字节形式的输入写入输出文件?

c# - 如何在不使用^的情况下实现XOR?

c++ - 在 C++ 中, "return;"是否与 "return NULL;"相同?

c++ - 防止C++中 namespace 中毒的绝佳方法

c++ - 为什么在我计算 NULL 指针时抛出异常(读取访问冲突)?

c++ - Unordered_map 与数据结构

c++ - 散列pair <pair <int,int>,pair <int,int >>的unordered_map