[英]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;
}
第二种情况给出了大量的编译错误。 从这个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;
}
这里的问题不是如何为std::unordered_map
编写哈希函数。 问题是,当std::map
不需要一个时,为什么需要一个?
我知道std::map
是一个二进制搜索树(BST),但是在非基本类型(int_pair)的键之间进行比较的确切程度如何呢?
std::map
不会散列任何东西。 它使用std::less
作为默认比较器。 它适用于任何支持operator<
类型。
std::unordered_map
使用std::hash
提供的哈希对其元素进行排序。
碰巧std::pair
提供了operator<
,但是没有std::hash
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.