C++ Unordered Map
C++ Unordered Map
In the Maps chapter, you learned that a map stores elements in key/value pairs, and keeps them sorted by key.
An unordered_map also stores key/value pairs, but it does not sort them. Because it does not have to keep the elements in order, it is usually faster to add and find elements, especially when there are many of them.
To use an unordered map, include the <unordered_map> library:
// Include the unordered_map library
#include <unordered_map>
Create and Access an Unordered Map
You create and use an unordered map in the same way as a map:
Example
unordered_map<string, int> people = { {"John", 32}, {"Adele", 45}, {"Bo", 29} };
cout << "John is: " << people["John"] << "\n";
cout << "Adele is: " << people["Adele"];
Add and Change Elements
Use square brackets [] to add a new element, or to change the value of an existing key:
Example
unordered_map<string, int> people = { {"John", 32}, {"Adele", 45}, {"Bo", 29} };
people["Jenny"] = 22; // Add a new element
people["John"] = 50; // Change the value of John
cout << "Jenny is: " << people["Jenny"] << "\n";
cout << "John is: " << people["John"];
Check if a Key Exists
Use count() to check if a key exists. It returns 1 if the key is found, and 0 if it is not:
Example
unordered_map<string, int> people = { {"John", 32}, {"Adele", 45}, {"Bo", 29} };
if (people.count("Adele")) {
cout << "Adele is in the map";
} else {
cout << "Adele is not in the map";
}
Loop Through an Unordered Map
You can loop through an unordered map with a for-each loop. But remember that the elements come in no particular order:
Example
unordered_map<string, int> people = { {"John", 32}, {"Adele", 45}, {"Bo", 29} };
int total = 0;
for (auto person : people) {
total += person.second;
}
cout << "Total age: " << total;
Map vs. Unordered Map
| map | unordered_map | |
|---|---|---|
| Order of elements | Sorted by key | No particular order |
| Speed | Fast | Usually faster |
| Use it when | You need the keys in order | You only need to store and find values |
Tip: In the same way, there is an unordered_set. It works like a set, but does not sort its elements. You will learn about it in the next chapter: Unordered Set.