【问题标题】:Why does std::map accept a std::pair as key, but std::unordered_map does not?为什么 std::map 接受 std::pair 作为键,但 std::unordered_map 不接受?
【发布时间】:2018-05-03 20:32:14
【问题描述】:

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

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

第二种情况会产生大量编译错误。从this SO questionthis 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) 的键之间的比较究竟如何?

【问题讨论】:

  • std::map 需要std::less&lt;T&gt;std::unordered_map 需要std::hash&lt;T&gt;,就这么简单。至于“为什么”,只需看看如何实现红黑树(map)和哈希表(unordered_map),你就会得到答案。
  • std::map 编译是因为 std::pair 有一个 operator&lt;std::less 调用,请参阅:en.cppreference.com/w/cpp/utility/pair/operator_cmp
  • @Neargye 你似乎没有理解这个问题,我问的是差异,而不仅仅是为什么 unordered_map 不能编译

标签: c++ hashmap binary-search-tree unordered-map std-pair


【解决方案1】:

std::map 不散列任何东西。它使用std::less 作为默认比较器。它适用于任何支持operator&lt; 的类型。

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

碰巧std::pair 提供了operator&lt;,但没有专门针对std::hash

【讨论】:

  • 感谢您的澄清,本质上归结为operator&lt;std::pair提供的事实
  • 对于那些想知道的人,你可以找到pair operators here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
相关资源
最近更新 更多