为什么 std::map 接受 std::p air 作为密钥,而 std::unordered_map 不接受?



在考虑重复之前,请先了解我问题的基础。

为什么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

最新更新