std::map &
unordered_map
Master C++ key-value containers: when to choose sorted trees vs. hash tables, how to insert, lookup, and iterate, and the complexity trade-offs that matter in real code.
What Is a Key-Value Container?
A key-value container stores data as pairs: every element has a unique key that maps to a value. Think of a dictionary: the word (key) points to its definition (value). In C++, the Standard Library provides two primary associative containers for this pattern.
Why Key-Value Storage Matters
Without associative containers, you would need to search through arrays or vectors linearly: \( O(n) \) per lookup. Key-value containers let you jump directly to the data you need.
Under the Hood: Tree vs. Hash Table
Declaring a Map
Core Operations
Complexity at a Glance
| std::map | std::unordered_map | |
|---|---|---|
| Insert | \( O(\log n) \) | \( O(1) \) avg |
| Lookup | \( O(\log n) \) | \( O(1) \) avg |
| Erase | \( O(\log n) \) | \( O(1) \) avg |
| Ordered iteration | ✓ yes | ✕ no |
| Worst-case lookup | \( O(\log n) \) | \( O(n) \) |
| Underlying structure | Red-black tree | Hash table |
operator[] vs. find()
Iterating Over a Map
How to Apply: Step by Step
Example 1: Word Counter
Count how many times each word appears in a list. Use operator[] to auto-initialise counts to 0.
Example 2: Sorted Phonebook
Store contacts and print them alphabetically. Here std::map is the right choice because we need sorted output.
Example 3: Safe Lookup Pattern
Check if a student exists without modifying the map. This is the safest general pattern for read access.
insert() vs. operator[]
Common Mistakes
Summary: map vs. unordered_map
| std::map | std::unordered_map | |
|---|---|---|
| Header | <map> | <unordered_map> |
| Order | Sorted by key | Unordered |
| Avg. access | \( O(\log n) \) | \( O(1) \) |
| Worst-case access | \( O(\log n) \) | \( O(n) \) |
| Key requirement | operator< |
std::hash + operator== |
| Memory | Lower overhead | Higher (hash buckets) |
| Best for | Sorted output, range queries | Maximum speed, no order needed |
Question 1 of 5
What is the average time complexity for looking up a key in std::unordered_map?
Question 2 of 5
Given std::map<std::string, int> m; what does m["test"] return if "test" is not in the map?
Question 3 of 5
Which container should you choose if you need to iterate over keys in alphabetical order?
Question 4 of 5
What is the correct way to check if a key exists in a map without modifying it?
Question 5 of 5
Consider the following code:
std::map<std::string, int> m;
m.insert({"a", 1});
m.insert({"a", 2});
m["a"] = 3;
What is the value of m["a"] after all three lines execute?