Map Lookup: find() vs. count() + at()

Question 21 / 51 Correct so far: 0 (0 answered)

Snippet A

Single Find

std::optional<int> lookup(const std::map<int, int>& m, int k) {
    auto it = m.find(k);
    if (it != m.end()) return it->second;
    return std::nullopt;
}

std::size_t total = 0;
for (int k : KEYS) {
    auto v = lookup(THE_MAP, k);
    if (v) total += static_cast<std::size_t>(*v);
}
Snippet B

Contains At

std::optional<int> lookup(const std::map<int, int>& m, int k) {
    if (m.count(k)) return m.at(k);
    return std::nullopt;
}

std::size_t total = 0;
for (int k : KEYS) {
    auto v = lookup(THE_MAP, k);
    if (v) total += static_cast<std::size_t>(*v);
}
Shared test data (shared-setup)
constexpr int kMapSize   = 4096;
constexpr int kQueries   = 65536;

static std::map<int, int> makeMap() {
    std::map<int, int> m;
    for (int i = 0; i < kMapSize; ++i)
        m[i * 2] = i;
    return m;
}

static std::vector<int> makeKeys() {
    std::vector<int> ks;
    ks.reserve(kQueries);
    for (int i = 0; i < kQueries; ++i)
        ks.push_back((i % (kMapSize * 3)) * 2 - kMapSize);
    return ks;
}

static const std::map<int, int> THE_MAP  = makeMap();
static const std::vector<int>   KEYS     = makeKeys();

Which snippet is faster?

Select the correct answer(s)