Codiqo

Learn C++ · lesson 30 of 61 · about 8 minutes

std::map

Meet the trader in the castle: store prices as key-value pairs in a std::map, look them up, and list them in key order.

What you'll learn

  • Create a map and insert pairs
  • Look up with [], at() and contains()
  • Loop over a map in key order

The trader's prices

Past the boss, the hero reaches a castle, and in its hall a trader sells potions, rope and a shield. Each thing has a price, so the prices are a std::map<std::string, int>: the name of a thing is the key, and its price in gold is the value. The trader lists everything for sale, and when the hero asks for something, the map is checked with contains() first, so asking for a thing that isn't sold never adds it to the list.

Look things up by key

std::map<std::string, int> prices; maps text keys to int values (#include <map>).

  • prices["tea"] = 2; adds or replaces a value
  • prices.at("tea") reads it, and throws if the key is missing
  • prices.contains("cake") checks without adding anything (C++20)
  • A map keeps its keys sorted, so loops visit them in order

A price list

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> prices = {{"tea", 2}, {"cake", 3}};
    prices["juice"] = 2;
    prices["tea"] = 3;
    std::cout << "Tea costs " << prices.at("tea") << "\n";
    std::cout << std::boolalpha << prices.contains("soup") << "\n";
    for (const auto& [item, price] : prices) {
        std::cout << item << ": " << price << "\n";
    }
}

Output

Tea costs 3
false
cake: 3
juice: 2
tea: 3

Tip

Reading prices["soup"] for a missing key silently adds soup with value 0. Use contains() or at() when you only want to read.

Tip

for (const auto& [item, price] : prices) gives each pair's key and value their own names. The const& reads each pair without copying it.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.