unordered_map容器

unordered_map 的介绍

用来快速检索,内部基于哈希,内部实现了一个哈希表,所以元素的排列顺序是杂乱无序的。
1通过key值快速检索value。
2内部是无序的map是有序的,会根据key排序
3每个值只能对应唯一一个键值,通过key的hash判断元素是否相同
4动态的管理内存
5.如果为非频繁的查询,容器元素小于1000,map比较稳定
如果非常高频的查询(100个元素以上),使用unordered_map比map快

定义与初始化

1 头文件

#include <unordered_map>

2 初始化

unoredered_map<const Key, T> map
`unordered_map<int, int> h;

3 遍历

用iterator迭代器遍历

unordered_map<int, int> h;
    
    for (int i = 4; i <= 9; i ++ ) h[i] = i - 4;
    
    unordered_map<int, int>::iterator it;
    for (it = h.begin(); it != h.end(); it ++ )
    cout << (*it).first << ' ' << (*it).second << endl;
    /*
    9 5
	5 1
	4 0
	6 2
	7 3
	8 4
	*/

用auto同样好用,可以达到iterator同样效果

for (auto it : h) cout << it.first << ' ' << it.second << endl;

用数组遍历

for (int i = 0; i <= 9; i ++ ) cout << h[i] << ' ' << endl;
/*
0 0 0 0 1 2 3 4 5
*/

迭代器

begin()
end()

函数

size()返回元素个数

cout << h.size() << endl;

insert插入元素

    unordered_map<int, int> h, h1;
    
    h.insert(unordered_map<int, int>::value_type(4, 1));
    h.insert(unordered_map<int, int>::value_type(5, 2));
    h.insert(unordered_map<int, int>::value_type(6, 3));
    h1.insert(h.begin(), h.end());
    for (auto it : h) cout << it.first << ' ' << it.second << endl;
    for (auto it : h1) cout <<it.first<<' '<<it.second<< endl;
    /*
    6 3
    4 1
    5 2
    5 2
    4 1
    6 3
    */

erase

for (int i = 4; i <= 7; i ++ ) h[i] = i - 4;
    
    h.erase(5);
    
    for (auto it : h) cout << it.first << ' ' << it.second << endl;
    /*
    7 3
	6 2
	4 0
	*/

清空

h.erase(h.begin(), h.end());

swap

clear

h.clear();

emplace

find

    if (h.find(5) != h.end()) puts("yes");
    else puts("no");

count

    cout << h.count(5) << endl;//1
    cout << h.count(7) << endl;//0

equal_range

猜你喜欢

转载自blog.csdn.net/qq_45914558/article/details/108622348