8.6 — map: look things up by name

📘 Chapter 8⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Key → value#

A map stores pairs: a key you look up, and a value you get back. Like a dictionary: word → meaning.

C++▶ Run
#include <iostream>#include <map>#include <string> int main(){    std::map<std::string, int> ages {        { "Ana", 12 },        { "Ben", 15 },    };     ages["Cleo"] = 11;               // add a new pair    std::cout << ages["Ben"] << '\n'; // 15    return 0;}

Does it have a key?#

C++
if (ages.contains("Dan"))   // C++20{    std::cout << "Dan is " << ages["Dan"] << '\n';}else{    std::cout << "No Dan here.\n";}
Watch out

ages["Dan"] adds Dan (with age 0) if he isn't there yet! Check with contains (or find) first if you only want to look.

Looping through a map#

A std::map keeps its keys sorted.

C++
for (const auto& [name, age] : ages){    std::cout << name << " is " << age << '\n';}
Output
Ana is 12Ben is 15Cleo is 11

Example: counting words#

C++
std::map<std::string, int> counts {};std::string word {};while (std::cin >> word){    ++counts[word];   // new words start at 0, then become 1}
Tip

std::unordered_map (from <unordered_map>) works the same way but is usually faster. It just doesn't keep keys in order.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.