The difference between c++ unordered_map and map

1. Introduction to unordered_map

The Chinese translation of unordered is "unordered". Naturally, unordered_map means an unsorted map. Unordered_set and set and unordered_map and map are comparable, and their differences are roughly the same.

Unordered_map is a standard template library added to c++11. Before c++11, standard templates such as unordered_map, unordered_set, auto, and stoi could not be used. unordered_map is included in the unordered_map header file, that is, if you want to use it, just introduce the following code

#include<unordered_map>
using namespace std;//注意需要使用命名空间

2. The difference between unordered_map and map

1. Realize different

  • The bottom layer of unordered_map is implemented with a hash table
  • The bottom layer of the map is implemented with a red-black tree

2. Different performance

  • Unordered_map is not sorted by key value, the insertion time is O(logn), and the query time is O(1)
  • The map is sorted by key value, the insertion time is O(logn), and the query time is O(logn)

3. The scope of use is different

  • The use of unordered_map is relatively limited. Its key can only be basic types such as int and double and string, not a self-defined structure
  • map can support all types of key-value pairs

3. Suggestions for use

Use unordered_map if you don’t need to sort by key value, if you really need it, map
unordered_set and set are the same

4. How to use

The use of unordered_map and map is almost the same, but the header files and definitions are different

The sample code for the definition is given below:

#include<iostream>
#include<map>//使用map需要的头文件 
#include<unordered_map>//使用unordered_map需要的头文件 
#include<set>//使用set需要的头文件 
#include<unordered_set>//使用unordered_set需要的头文件 
using namespace std;
int main(){
    
    
	map<int,int> m1;
	unordered_map<int,int> m2;

	set<int> s1;
	unordered_set<int> s2;
}

If you want to learn how to use map, you can read my other article.
Introduction to c++ map usage must read super detailed

If you want to learn how to use set, you can read my other article.
Introduction to c++ set usage must read super detailed

dev c++ does not use c++11 by default, if you want to use it, you can read my other article
dev uses c++11 tutorial

Finally, come on! Brother cute! !

Guess you like

Origin blog.csdn.net/weixin_52115456/article/details/127698255