std::map and std::unordered_map
Key-value lookups in C++, the difference between map and unordered_map, and the operator[] insertion trap.
Both store key-value pairs with unique keys:
std::map |
std::unordered_map |
|
|---|---|---|
| Built on | balanced tree | hash table |
| Lookup | O(log n) | O(1) on average |
| Order | sorted by key | none |
Use unordered_map for fast lookups and map when you need keys in order. Watch out: m[key] inserts a default value if the key is missing. To check without inserting, use m.contains(key) (C++20) or m.find(key).
Example
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> ages{{"Linus", 55}, {"Ada", 36}};
ages["Grace"] = 85;
for (const auto &[name, age] : ages) std::cout << name << "=" << age << " ";
std::cout << "\n" << ages.contains("Alan") << " " << ages.size() << "\n";
return 0;
}
Output:
Ada=36 Grace=85 Linus=55
0 3