Lesson 181 +10 XP

Maps (std::map)

Maps (std::map)

A std::map stores key-value pairs. You give it a key and the map knows the value belonging to that key - like looking up a phone book entry by name.

Create a map

#include <map>

std::map<std::string, int> ages;
ages["John"] = 30;
ages["Mary"] = 25;

The first part is the key type (std::string), and the second is the value type (int). Each key is unique inside one map.

Add or change with []

Using [] with a missing key inserts a new pair; reusing an existing key overwrites that value:

ages["John"] = 31;   // updates John to 31

Iterate the pairs

for (auto const& p : ages) {
    std::cout << p.first << ": " << p.second << "\n";
}

Each pair has first (the key) and second (its value).

Find an entry safely

auto it = ages.find("John");
if (it != ages.end()) {
    std::cout << it->second << "\n";   // prints John's value
}

find returns an iterator to the entry, or end() if the key does not exist. Compare to end() before reading the value.

TL;DR

  • A std::map pairs unique keys with values.
  • ages["John"] = 30 inserts or updates an entry.
  • Iterate the map; each p.first is a key and p.second is a value.
  • find(key) returns an iterator or end() when missing.
  • Perfect for fast lookups "give me the value for this name".