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

原文链接: https://www.cnblogs.com/sectumsempra/p/17065181.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ STL unordered_map

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/313653

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 下午12:59
下一篇 2023年2月16日 下午12:59

相关推荐