All lessons

Maps

8 min · C++

Look up values by key with std::map, C++'s dictionary.

C++ · Maps0/5 cleared

Enemy 1 of 5

Key-value lookups

This code makes a map that stores a score under the name Ada, then reads it back by that name. Press Run to see 10 printed.

Why this works

So far, vectors have let you look things up by position (index 0, 1, 2...). A std::map<Key, Value> (from <map>) instead lets you look things up by a meaningful key (a player's name, an item id, a word) rather than a numeric position. Internally it keeps entries sorted by key, which is why it's sometimes called an "ordered map".

Reading and writing use the same square-bracket syntax you've already seen with vectors: m[key] = value stores a value under that key, and m[key] reads it back. If you read a key that was never stored, std::map quietly creates it with a default value (0 for numbers, an empty string for text) rather than crashing. Worth knowing, since it means a typo'd key won't necessarily throw an error.

This is conceptually the same idea as a Python dict, a JavaScript object, or a Go map. Every mainstream language has some version of this key-value structure, because looking things up by a meaningful name instead of a numeric position is such a common need.

You
Pincer Crab
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.