#include<unordered_map>
头文件
using namespace std;
作用
无序map容器。以pair形式存储数据。pair在#include<utility>
头文件中定义。pair:<key, value>
pair其实就是数据结构与算法课写的Record类型
对比map
- map内部利用红黑树原理默认实现了key值的递增排序;unordered_map是无序的;
- 创建时unordered_map更耗时,但查询速度更快;
创建
unordered_map<int, int>hashmap;
前两个必填,最多四参数。
template < class Key, // unordered_map::key_type
class T, // unordered_map::mapped_type
class Hash = hash<Key>, // unordered_map::hasher
class Pred = equal_to<Key>, // unordered_map::key_equal
class Alloc = allocator< pair<const Key,T> > // unordered_map::allocator_type
> class unordered_map;
常用函数
1. 访问方法
- 下标索引
value = hashmap[target];/*这个pair 格式为 <target, value>*/
- 利用迭代器iterator
auto iter = hashmap.find(target);
key = iter->first;
value = iter->second
unordered_map<Key,T>::iterator it;
(*it).first; // the key value (of type Key)
(*it).second; // the mapped value (of type T)
(*it); // the "element value" (of type pair<const Key,T>)
2. find(key)
- 找到:return指向这个pair的正向迭代器iterator。
- 没找到:return指向容器中最后一个pair之后位置的迭代器使用
end()
返回的迭代器 。
使用
if(hashmap.find(target) != hashmap.end()){
return /* 找到了 */;
}
3. 插入
emplace
比insert
方法效率更高,两种都OK。
hashmap.insert(5,22);
hashmap.emplace(1,88);