首页 > 解决方案 > 为什么 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)的键之间的比较究竟是如何进行的?

标签: c++hashmapbinary-search-treeunordered-mapstd-pair

解决方案


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

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

碰巧std::pair提供了operator<,但没有专门化std::hash


推荐阅读