c++ - 为什么 std::map 接受 std::pair 作为键,但 std::unordered_map 不接受?
问题描述
在考虑重复之前,请了解我的问题的基础。
为什么 C++std::map
接受 astd::pair
作为键类型,但 astd::unordered_map
不接受?
第一个案例编译完美:
#include <map>
#include <utility>
using namespace std;
typedef pair<int,int> int_pair;
int main()
{
map<int_pair,int> m;
return 0;
}
第二种情况给出了大量的编译错误。从这个 SO question和这个 SO question中可以清楚地看出,必须创建自定义哈希函数和等价运算符。
#include <unordered_map>
#include <utility>
using namespace std;
typedef pair<int,int> int_pair;
int main()
{
unordered_map<int_pair,int> m;
return 0;
}
这里的问题不是如何为std::unordered_map
. 问题是,当不需要一个时,为什么std::map
根本需要一个?
我知道这std::map
是一个二叉搜索树(BST),但是对于非基本类型(int_pair)的键之间的比较究竟是如何进行的?
解决方案
std::map
不散列任何东西。它std::less
用作其默认比较器。它适用于任何支持operator<
.
std::unordered_map
使用由 提供的哈希对其元素进行排序std::hash
。
碰巧std::pair
提供了operator<
,但没有专门化std::hash
。
推荐阅读
- sql - 排除满足特定条件的元素的查询
- javascript - 不理解 JS 装饰器中的构造
- python - 如何 Cythonize Python Enum mixin 类?
- python - 如何在 Unittest 中使用多个失败并将它们打印为失败而不结束测试?
- openshift - 为什么选择 Spring Cloud 而不是即用型 Paas(如 Cloud Foundry)?
- numpy - ImportError:liblapack.so.3gf:无法打开共享对象文件:没有这样的文件或目录
- javascript - Text is overflowing in code tag instead of scroll
- python - 将 base64 字符串转换为 numpy 图像数组会将图像输出更改为略蓝的颜色
- numpy - 如何创建大 np.zeros 矩阵?
- scala - 如何在 Flink 中为 WindowFunction 将 fold() 转换为 AggregateFunction?