C++ STL unordered_map

#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. 访问方法

  1. 下标索引
value = hashmap[target];/*这个pair 格式为 <target, value>*/
  1. 利用迭代器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. 插入

emplaceinsert方法效率更高,两种都OK。

hashmap.insert(5,22);
hashmap.emplace(1,88);

4. 大小

hashmap.size()

参考资料:
http://c.biancheng.net/view/7231.html

posted @   地尽头  阅读(78)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示