How to Look up Values in a Map -- Sandor Dargo
Whether you’re in a coding interview or writing production code, you’ll eventually face the question: What’s the right way to look up values in a
std::map
or std::unordered_map
? For simplicity, we’ll refer to both containers as maps in this post.
How to Look up Values in a Map
by Sandor Dargo
From the article:
Let’s explore the different options — along with their pros and cons.
operator[]
Using
operator[]
is the old-fashioned way to access elements of a map. It takes a key and returns a reference to the corresponding value. The complexity is log(n) forstd::map
and average constant time (with worst-case linear) forstd::unordered_map
.However, there’s a big caveat.
What if the key is not present in the map?
Unlike a
vector
— where accessing an invalid index withoperator[]
leads to undefined behavior — amap
will instead insert a new entry with the given key and a default-constructed value. This side effect makesoperator[]
unsafe for lookups where insertion is not desired.