October 2025

How to Look up Values in a Map -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGWhether 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) for std::map and average constant time (with worst-case linear) for std::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 with operator[] leads to undefined behavior — a map will instead insert a new entry with the given key and a default-constructed value. This side effect makes operator[] unsafe for lookups where insertion is not desired.