I encountered a problem when I was coding today,
unordered_map1.insert(std::pair<Qstring, Camera>(str, cur_cam));
Immediately after this sentence, an error was reported. After careful query, the solution was obtained. The key of the map can use the structure defined by itself, but the unordered_map cannot.
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
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, map if you really need it
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;
}