[ C++ STL ] STL中的unordered_map

咳咳 在学校就不好好学C++ 现在惨了吧 啥也不会
好 那么来补充一下关于unordered_map的一些简单操作吧

定义

它叫做:无序映射。
C++ STL中的unordered_map实现使用了哈希表,在O(1)的时间实现对元素的查找,但是相应地在空间的开销增大了。
一些资料上比较了它和map的特点,我这C++还抓瞎的崽,暂时不进行拓展了,红黑树的特点我还没看呢...
STL中的map对应的数据结构是红黑树,红黑树内的数据时有序的,在红黑树上查找的时间复杂度是O(logN),相对于unordered_map的查询速度有所下降,但额外空间开销减小。

常用函数

声明

#include <unordered_map>
using namespace std;
// <.., ..> 中指明两个变量类型,key-value
unordered_map<string, int> map; 

容器大小

cout << map.empty() << endl;
cout << map.size() << endl;

插入键值对

map['A'] = 1; 
// or
map.insert(make_pair('A', 1));

判断key值是否存在

假设我们要检验 'B' 是否在我们刚刚声明的map中,可以用unordered_map的成员函数:find()函数和end()函数。
注意这里find()和end()所返回的数据类型均为iterator。
在unordered_map中,如果find()没找到要找的key,就返回和end()一样的iterator值。

// 'B' is not a key
if(map.find('B') == map.end()) {
    // your code
}
// or
if(map.count('B') == 0) {
    // your code
}

移除元素

移除元素有三种形式,按照范围和key值进行删除。

//删除元素
second.erase ( second.begin() );      // erasing by iterator
second.erase ('a');             // erasing by key
second.erase ( second.find('c'), second.end() ); // erasing by range

其他

map.clear(); // 清空

猜你喜欢

转载自www.cnblogs.com/recoverableTi/p/12641366.html