【发布时间】: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 question 和this 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<T>而std::unordered_map需要std::hash<T>,就这么简单。至于“为什么”,只需看看如何实现红黑树(map)和哈希表(unordered_map),你就会得到答案。 -
std::map编译是因为std::pair有一个operator<由std::less调用,请参阅:en.cppreference.com/w/cpp/utility/pair/operator_cmp -
@Neargye 你似乎没有理解这个问题,我问的是差异,而不仅仅是为什么 unordered_map 不能编译
标签: c++ hashmap binary-search-tree unordered-map std-pair