C++STL common operations of unordered_map and map

C++STL common operations of unordered_map and map

Introduction:

The contents stored in map and unordered_map are the same, both are (key, value).

the difference:

1. The map has a built-in red-black tree, and unordered_map has a built-in hash table.

2. The map has a sorting function, and the elements in unordered_map are unordered.

3. The time complexity of map query, insertion and deletion operations is O(logn), and the search time complexity of unordered_map is O(1).

4. Because of the built-in red-black tree in map, each node has to store the parent node and other content additionally, so the memory footprint is larger, but the unordered_map is even larger!

Note: Although the query time of the hash table is O(1), the query time of unordered_map is not necessarily shorter than that of map. Considering the amount of data, because the hash function construction speed of unordered_map is relatively slow, it should Specific situation, specific analysis, specific choice!

#include<unordered_map>

Common operations:

#include<iostream>
#include<unordered_map>
#include<string>
using namespace std;
int main() {
    
    
    unordered_map<int,string> um;
    um.insert(pair<int,string>(1,"one"));       //一般插入
    um[3] = "three";                                    //数组的形式,如果存在就修改,否则插入
    um.insert(pair<int,string>(2,"two"));
    um[2] = "twotwo";                                   //修改
    for(auto it = um.begin();it != um.end();++it)       //begin,end,迭代器
        cout<<it->first<<" "<<it->second<<"\n";
    cout<<"um'size = "<<um.size()<<"\n";                //size
    if(um.empty())                                      //empty
        cout<<"um is empty!"<<"\n";
    else
        cout<<"um is not empty"<<"\n";
    auto it = um.find(1);                            //find
    if(it != um.end())
        cout<<it->first<<" "<<it->second<<"\n";
    cout<<um.count(2)<<"\n";                         //count
	return 0;
}
Output:
2 twotwo
1 one
3 three
um'size = 3
um is not empty
1 one
1

Guess you like

Origin blog.csdn.net/qq_45985728/article/details/113663410