C++ Programming: Objects, RAII and the STL ยท The Standard Library

std::map

Key-value lookups with keys kept in sorted order, and loops with structured bindings.

maps.cpp

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> stock;            // keys kept in sorted order
    stock["pear"] = 2;
    stock["apple"] = 5;
    stock["apple"] += 3;
    int kiwis = stock.count("kiwi");   // 0: not there
    int total = 0;
    for (const auto &[fruit, qty] : stock) {
        total += qty;
    }
    cout << stock.size() << " " << kiwis << " " << total << endl;
    return 0;
}

Step by step

  1. stock is created on the stack with the value {}.
  2. stock["pear"] = 2 inserts the key.
  3. stock changes from {pear: 2} to {apple: 5, pear: 2}.
  4. apple: 5 + 3 = 8.
  5. count("kiwi") is 0: no such key.
  6. total is created on the stack with the value 0.
  7. fruit is created on the stack with the value "apple". qty is created on the stack with the value 8.
  8. Keys come out sorted: apple first.
  9. fruit changes from "apple" to "pear". qty changes from 8 to 2.
  10. total changes from 8 to 10.
  11. fruit goes out of scope and disappears. qty goes out of scope and disappears.
  12. It prints 2 0 10.
  13. The method returns 0.
  14. 2 0 10.