Module 8 · The Standard Template Library — topic 5 of 7
Maps (std::map and std::unordered_map)
Key–value storage: sorted std::map versus hashed std::unordered_map, insert/find/erase, the operator[] trap, counting frequencies and iterating in order.
Learning objectives
- Insert, look up and erase entries safely
- Choose between map and unordered_map
- Count frequencies and iterate in sorted order
Definition
std::mapis an associative container of unique keys kept in sorted order (typically a red-black tree, O(log n) operations);std::unordered_mapstores keys in a hash table with average O(1) operations and no ordering.
Introduction
A map answers “what is the value for this key?” — a phone book, a word count, a cache. C++ offers two: std::map keeps keys sorted, std::unordered_map uses hashing for faster average lookup.
Why it matters
Maps appear in almost every real program and many interview problems (two-sum, anagrams, frequency counts).
Misusing operator[] for lookups silently inserts keys — a common bug.
Detailed explanation
m[key] returns a reference, inserting a default value if the key is missing. Use it to write or to count (++m[word]).
For lookups use find (returns end() if absent), count/contains (C++20) or at (throws if absent).
insert({k, v}) doesn't overwrite an existing key; insert_or_assign (C++17) does; try_emplace constructs only if absent.
Iterating a map visits keys in ascending order; unordered_map order is unspecified.
Custom key types need operator< for map, or a hash and == for unordered_map.
Syntax
- Elements are
std::pair<const Key, Value>. it->firstis the key,it->secondthe value.- Keys can't be modified in place.
Code examples
Counting with operator[]
c 3 java 1 python 2
Safe lookup
book: 250 bag: not found 2 items
More examples
Grouping anagrams with unordered_map
act: cat act eggloo: google gogole eilnst: listen silent enlist 1 99
Step-by-step explanation
- Sorting a word's letters gives a key shared by all its anagrams.
groups[key]creates an empty vector the first time and appends to it.- Copying into a
std::mapsorts the groups so output is deterministic. insertkeeps the existing value;insert_or_assignreplaces it.
Expected output
Running “Grouping anagrams with unordered_map” prints exactly:
Practical applications
- Caches map keys to computed results.
- Routers map addresses to handlers.
- Compilers map identifiers to symbols.
Best practices
- Use find/contains/at for lookups.
- Use unordered_map for speed and map when order matters.
- Reserve buckets for large unordered_maps.
Common mistakes
Lookup with operator[] inserts
Avoid
Prefer
operator[] creates the key with a default value.
Relying on unordered_map order
Avoid
Prefer
Hash table order is unspecified and can change between runs and compilers.
Important notes
operator[]requires a default-constructible value type and can't be used on a const map.- unordered_map worst case is O(n) with many collisions.
Key takeaways
- map is sorted (O(log n)); unordered_map is hashed (O(1) average).
[]inserts missing keys;finddoesn't.- Iterate maps with structured bindings.
Try it yourself
- 1Solve two-sum: find two indices whose values add up to a target using an unordered_map.
- 2Build a phone book with add, find and delete commands.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
7 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat does `m["missing"]` do on a std::map<std::string, int> when the key is absent?
- ModerateWhat is printed?