Key Lookup: std::map vs std::unordered_map
Question 5 / 12 • Correct so far: 0 (0 answered)
Map Lookup
int findValue(const std::map<int, int>& m, int key) {
auto it = m.find(key);
return it != m.end() ? it->second : -1;
}
int sum = 0;
for (int key : lookup_keys)
sum += findValue(ordered_map, key); Unordered Map Lookup
int findValue(const std::unordered_map<int, int>& m, int key) {
auto it = m.find(key);
return it != m.end() ? it->second : -1;
}
int sum = 0;
for (int key : lookup_keys)
sum += findValue(hash_map, key); Shared test data (shared-setup)
constexpr int MAP_SIZE = 1000;
static std::map<int, int> ordered_map;
static std::unordered_map<int, int> hash_map;
static std::vector<int> lookup_keys;
struct MapInit {
MapInit() {
for (int i = 0; i < MAP_SIZE; ++i) {
ordered_map[i] = i * 2;
hash_map[i] = i * 2;
lookup_keys.push_back(i);
}
}
} _map_init; Which snippet is faster?
Snippet B is faster because std::unordered_map uses a hash table, giving average O(1) lookup per key. std::map uses a balanced binary tree (red-black), requiring O(log n) comparisons per lookup. For integer keys with a cheap hash, the hash table avoids the logarithmic tree traversal entirely, so the gap widens as the container grows.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Map Lookup | 8.16 us | 1.0× |
| Unordered Map Lookup | 1.31 us | 6.2× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.