在考虑重复之前,请先了解我问题的基础。
为什么C++std::map
接受std::pair
作为密钥类型,而std::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 问题和这个 SO 问题中可以清楚地看出,必须创建自定义哈希函数和等价运算符。
#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
。