在考虑复制之前,请了解我的问题基础。
为什么C++的std::map可以接受std::pair作为键类型,但std::unordered_map却不行?
第一种情况可以完美编译:
第二个案例出现了很多编译错误。从这个SO问题和这个SO问题中可以清楚地看到,必须创建一个自定义的哈希函数和等价运算符。
这里的问题不是如何为std :: unordered_map编写哈希函数。问题在于,为什么需要哈希函数,而std :: map则不需要?
我知道std :: map是一棵二叉搜索树(BST),但对于非基本类型(int_pair)的键之间的比较究竟是如何进行的?
为什么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<T>
,而std::unordered_map
需要std::hash<T>
,就是这么简单。至于“为什么”,只需查找如何实现红黑树(map)与哈希表(unordered_map),然后你就会得到答案。 - Cory Kramerstd::map
可以编译,因为std::pair
有一个被std::less
调用的operator<
。请参见:http://en.cppreference.com/w/cpp/utility/pair/operator_cmp - Richard Critten