Key Lookup: std::map vs std::unordered_map

Question 5 / 12 Correct so far: 0 (0 answered)

Snippet A

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);
Snippet B

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?

Select the correct answer(s)