stl · high
map vs unordered_map
Same keys in a sorted red-black tree vs hash buckets - compare lookup cost, collisions, and iteration order.
🔑 Key line
map = sorted red-black tree (O(log n)); unordered_map = hash buckets (O(1) avg). Choose by whether you need order.
The code
std::map<int, V> m; // balanced BST (red-black tree)std::unordered_map<int, V> u; // hash table (buckets)// both hold keys 1..5
m.find(5); // O(log n): walk root -> 4 -> 5u.find(5); // O(1) avg: hash(5) % 4 -> bucket 1
for (auto& kv : m) {} // visits 1 2 3 4 5 (sorted)for (auto& kv : u) {} // visits 4 1 5 2 3 (bucket order)What this lesson walks through
- 01Same keys, two data structures
- 02std::map = red-black tree (sorted)
- 03std::unordered_map = hash buckets
- 04find(5) in map: O(log n)
- 05find(5) in unordered_map: O(1) avg
- 06Collisions -> chaining
- 07Iteration order differs
- 08Which one to use
std::map and std::unordered_map both map keys to values, but store them completely differently. Here both hold keys 1..5.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of map vs unordered_map and 100+ animated C++ interview lessons.