Why does std::map accept a std::pair as key, but std::unordered_map does not?(为什么std::map接受std::对作为键,而std::unordered_map不接受呢?)
问题描述
在考虑复制之前,请了解我的问题的基础。
为什么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
作为其默认比较器。它将适用于支持operator<
的任何类型。
std::unordered_map
使用std::hash
提供的哈希对其元素进行排序。
碰巧std::pair
提供operator<
,但没有std::hash
的专门化。
这篇关于为什么std::map接受std::对作为键,而std::unordered_map不接受呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么std::map接受std::对作为键,而std::unordered_map不接受呢?


- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- GDB 不显示函数名 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- XML Schema 到 C++ 类 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01