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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |