unordered_map容器

Introduction to unordered_map

Used for fast retrieval, the internal is based on hash, and a hash table is implemented internally, so the order of the elements is disorderly.
1 Quickly retrieve value by key value.
2 The internally unordered map is ordered and will be sorted according to the key.
3 Each value can only correspond to a unique key value, and the key’s hash is used to determine whether the elements are the same.
4 Dynamic management of memory
5. If it is an infrequent query, The container element is less than 1000, and the map is relatively stable. For
very high frequency queries (more than 100 elements), using unordered_map is faster than map

Definition and initialization

1 header file

#include <unordered_map>

2 initialization

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

3 traversal

Traverse with 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
	*/

It is also easy to use with auto and can achieve the same effect as iterator

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

Iterate with array

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

Iterator

begin()
end()

function

size() returns the number of elements

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

insert insert element

    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
	*/

Empty

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

Guess you like

Origin blog.csdn.net/qq_45914558/article/details/108622348