Map Lookup: find() vs. count() + at()
Question 21 / 51 • Correct so far: 0 (0 answered)
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);
} 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?
Snippet A is faster. map.find() locates the element in one tree traversal and returns an iterator used for both the existence check and value access. map.count() followed by map.at() traverses the tree twice for the same key, doubling the lookup work.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Contains At | 1.23 ms | 1.0× |
| Single Find | 1 ms | 1.2× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.