在考虑重复之前,请先了解我的问题的基础。
为什么 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;
}
第二种情况会出现大量编译错误。已经可以清楚地看出这个问题 https://stackoverflow.com/questions/32685540/ and 这个问题 https://stackoverflow.com/questions/33597127/必须创建自定义哈希函数和等价运算符。
#include <unordered_map>
#include <utility>
using namespace std;
typedef pair<int,int> int_pair;
int main()
{
unordered_map<int_pair,int> m;
return 0;
}
问题在这里is not如何编写哈希函数std::unordered_map
。问题是,当std::map
不需要一个吗?
I know std::map
是二叉搜索树 (BST),但是非基本类型 (int_pair) 的键之间究竟是如何进行比较的呢?
std::map http://en.cppreference.com/w/cpp/container/map不散列任何东西。它用std::less http://en.cppreference.com/w/cpp/utility/functional/less作为其默认比较器。它将适用于任何支持的类型operator<
.
std::unordered_map http://en.cppreference.com/w/cpp/container/unordered_map使用以下提供的哈希对其元素进行排序std::hash http://en.cppreference.com/w/cpp/utility/hash.
碰巧的是std::pair http://en.cppreference.com/w/cpp/utility/pair/operator_cmp提供operator<
,但没有专门针对std::hash
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)