无序映射的键

Keys of unordered_map

本文关键字:映射 无序      更新时间:2023-10-16

在C++11中构造一个无序映射时,对键和值的数据类型有什么样的限制?

我试图创建这个:

unordered_map<vector<int>, int>

这给了我一个编译错误。我需要写我自己的hasher吗?

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的评论所说:

如果您更喜欢另外,运算符==也必须可用于关键对象,或者指定为第四个模板参数的比较。