DMarlon Studio

Lesson 15 · 15 of 20

Maps · C++

Store key-value pairs in C++ with std::map: a greengrocer's stock with [], count(), erase() and a walk through the keys in order.

C++ · Maps in DMarlon Studio: the example's code and its output in the terminal

`std::map` links keys to values, like a dictionary. It is declared with both types: std::map<std::string, int> goes from a fruit's name to its amount. It needs #include <map>.

`[]` reads a key's value (stock["apples"] gives 12) and also changes it, or creates the key if it is missing: stock["kiwis"] = 20 adds the kiwis. Careful: merely reading stock["bananas"] would create it too, with the value 0.

To check for a key without creating it there is `count()`, which in a map gives 0 or 1. `erase()` removes a key together with its value. And at(), as with vectors, throws an error if the key does not exist.

A map keeps its keys sorted: walking through it gives apples, kiwis and pears, in alphabetical order rather than the order they were added. Each element is a pair: item.first is the key and item.second the value.

Counting is a classic job: letters[c]++ works even when the letter is not there yet, because [] creates it with 0 and then adds one. That is how the letters in banana are counted.

Code · main.cpp

#include <iostream>#include <map>#include <string>int main() {    // A map links keys to values, and keeps the keys in order.    std::map<std::string, int> stock = {{"pears", 5}, {"apples", 12}, {"plums", 0}};    std::cout << "Apples: " << stock["apples"] << '\n';    // [] changes a value, or creates the key if it is new.    stock["pears"] = 8;    stock["kiwis"] = 20;    // count() checks a key without creating it (0 or 1).    if (stock.count("bananas") == 0) std::cout << "No bananas today\n";    // erase() removes a key together with its value.    stock.erase("plums");    // Each element is a pair: first is the key and second, the value.    int pieces = 0;    for (const auto& item : stock) {        std::cout << item.first << ": " << item.second << '\n';        pieces += item.second;    }    std::cout << stock.size() << " fruits, " << pieces << " pieces\n";    // Counting is a classic job: a missing key starts at 0.    std::map<char, int> letters;    for (char c : std::string("banana")) letters[c]++;    for (const auto& item : letters) std::cout << item.first << '=' << item.second << ' ';    std::cout << '\n';    return 0;}

Output · c++ -std=c++17 main.cpp -o main && ./main

Apples: 12
No bananas today
apples: 12
kiwis: 20
pears: 8
3 fruits, 40 pieces
a=3 b=1 n=2

Key points

  • std::map<Key, Value> links keys to values.
  • m[key] = value changes or adds.
  • Reading m[key] creates the key if it is missing.
  • count() checks a key without creating it and erase() removes it.
  • Keys always come out in order.

Exercise

Use a std::map<std::string, int> to count how many times each colour appears in a vector {"red", "blue", "red", "green", "blue", "red"} and print the result.