What is the difference between std::map and std::unordered_map?
| Point | std::map | std::unordered_map |
|---|---|---|
| Inside | Balanced tree | Hash table |
| Order | Sorted by key | No order |
| Find, insert | O(log n) | O(1) on average |
| Key needs | operator< | hash and == |
| Iterators | Stay valid after insert | Can be invalidated by a rehash |
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>
int main() {
std::map<std::string, int> sorted{{"pear", 3}, {"apple", 1}, {"mango", 2}};
for (const auto& [k, v] : sorted) std::cout << k << ' '; // always sorted
std::cout << '\n';
std::unordered_map<std::string, int> fast{{"pear", 3}, {"apple", 1}};
std::cout << fast.at("pear") << ' ' << fast.contains("kiwi") << '\n';
}
Output
apple mango pear
3 0
Choose unordered_map when you only look up by key. Choose map when you need the order or range searches. See STL Containers.
Learn more about the similar topics:
| Tutorials |
|---|
| C++ Templates and Generic Programming |
| C++ STL Containers: map, set, unordered_map, queue and stack |
| C++ Algorithms and Iterators |
| Exercises & Assignments |
|---|
| Write a generic maximum template |
| Count the frequency of words with a map |
| Remove duplicates from a vector and keep the order |