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

Why does std::map accept a std::pair as key, but std::unordered_map does not?

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

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

第二种情况给出了大量的编译错误。从 and 可以清楚地看出,必须创建自定义哈希函数和等价运算符。

#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 doesn't hash anything. It uses std::less 作为默认比较器。它适用于支持 operator<.

的任何类型

std::unordered_map sorts its elements using a hash provided by std::hash.

碰巧 std::pair 提供 operator<,但没有 std::hash 的专业化。