为什么std :: map接受std :: pair作为键,但std :: unordered_map不接受?

Max*_*Max 2 c++ unordered-map hashmap binary-search-tree std-pair

在考虑重复之前,请理解我的问题的基础.

为什么C++ std::map接受a std::pair作为键类型,但是a 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;
}
Run Code Online (Sandbox Code Playgroud)

第二种情况给出了大量的编译错误.从这个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;
}
Run Code Online (Sandbox Code Playgroud)

这里的问题不是如何编写哈希函数std::unordered_map.问题是,为什么在不需要的时候std::map需要一个人?

我知道std::map是一个二进制搜索树(BST),但是在非基本类型(int_pair)的键之间进行比较的确切程度如何呢?

Fra*_*eux 7

std::map不散列任何东西.它std::less用作默认比较器.它适用于任何支持的类型operator<.

std::unordered_map使用提供的哈希对其元素进行排序std::hash.

它恰好std::pair提供了operator<,但没有专门化std::hash.