Maps
Map
Stores unique keys
Keys are sorted
Implemented using a Red-Black Tree
Keys are immutable
Elements stored as:
Access methods
operator[]
If key 5 does not exist:
It gets inserted
Value is default-constructed
at()
Throws exception if key not found
Does not insert
Operations on map
Iteration
Always in sorted key order.
Lower and upper bound on map
Used in Range queries.
Multimap
Same as map
Allows duplicate keys
Still sorted
Still tree-based
Map vs Multimap
Feature | map | multimap |
|---|---|---|
Duplicate keys | ❌ | ✅ |
operator[] | ✅ | ❌ |
Sorted | ✅ | ✅ |
No [] operator in multimap. Because which value would it return? Exactly.
Accessing all values for a key
Erase behavior
Unordered Map
Stores unique keys
No ordering
Implemented using a hash table
Faster on average
No range queries
You do not get:
lower_boundupper_boundSorted iteration
Hashing
Built-in types works
Custom keys need a custom hash
Summary
Operation | map / multimap | unordered_map |
|---|---|---|
Insert | O(log n) | O(1) avg |
Find | O(log n) | O(1) avg |
Erase | O(log n) | O(1) avg |
Order | Sorted | None |
Use map when:
You need sorted keys
You need range queries
Deterministic iteration order matters
Use multimap when:
One key maps to multiple values
Order matters
Duplicates are intentional
Use unordered_map when:
Order doesn’t matter
Performance is critical