Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

std::map and algorithms

By the end of this chapter, you'll be able to

  • Associate keys with values with std::map
  • Go through a map and test whether a key is present
  • Sort and search a vector with std::sort and std::find
  • Write a small lambda function to customise an algorithm

std::map: a dictionary

A std::map associates keys with values, the way a phone book associates a name with a number. Each key is unique, and the map keeps them sorted.

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

int main() {
    std::map<std::string, int> stock = {{"rice", 40}, {"oil", 12}};
    stock["sugar"] = 25;          // adds a key
    stock["rice"] -= 5;           // changes an existing value

    for (const auto& [product, quantity] : stock) {
        std::cout << product << ": " << quantity << "\n";
    }
    if (stock.contains("flour")) {
        std::cout << "Flour in stock\n";
    } else {
        std::cout << "No flour\n";
    }
    return 0;
}
oil: 12
rice: 35
sugar: 25
No flour
  • std::map<std::string, int>: keys of type std::string, values of type int. You need #include <map>.
  • stock["sugar"] accesses the value of the key "sugar", and creates it if it doesn't exist.
  • The loop goes through the pairs in key order (alphabetical here). const auto& [product, quantity] gives a name to the key and the value of each pair: this is a structured binding.
  • contains(key) (C++20) tests whether a key is present without creating it.

We display the number of times "the" appears.

Step 6 of 6
Text description of the animation
  1. We count the words of a tiny sentence.
  2. The map is empty.
  3. "the" doesn't exist: counts[word] creates it with the value 0, then ++ turns it into 1.
  4. Same for "cat". The map keeps its keys in alphabetical order.
  5. "the" already exists: its value becomes 2.
  6. We display the number of times "the" appears.

The algorithms in <algorithm>

The <algorithm> library contains dozens of functions that work on ranges of items, given by a beginning and an end: v.begin() and v.end().

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> times = {42, 17, 35, 8, 29};

    std::sort(times.begin(), times.end());
    for (int t : times) std::cout << t << " ";
    std::cout << "\n";

    auto it = std::find(times.begin(), times.end(), 35);
    if (it != times.end()) {
        std::cout << "35 found at index " << (it - times.begin()) << "\n";
    }

    std::sort(times.begin(), times.end(), [](int a, int b) { return a > b; });
    std::cout << "Slowest time: " << times.front() << "\n";

    auto fast = std::count_if(times.begin(), times.end(), [](int t) { return t < 30; });
    std::cout << fast << " times under 30 s\n";
    return 0;
}
8 17 29 35 42 
35 found at index 3
Slowest time: 42
3 times under 30 s
  • std::sort(begin, end) sorts in increasing order.
  • std::find(begin, end, value) returns an iterator, a kind of cursor pointing at the item found. If it finds nothing, it returns end: you must always compare the result with end() before using it.
  • [](int a, int b) { return a > b; } is a lambda: a small nameless function, written right where you need it. Here, it tells std::sort to sort in decreasing order.
  • std::count_if counts the items for which the lambda returns true.

Your turn

Worked exercise

Worked exercise: the most frequent word

Read words from the keyboard until the end of input, count them with a std::map, then display the most frequent word and its number of appearances. In case of a tie, keep the first one in alphabetical order.

Hint 1
while (std::cin >> word) { counts[word]++; } fills the map.
Hint 2
Go through the map keeping the best word and its count. Since the map is sorted, if you only replace when the count is strictly greater, you keep the first one in case of a tie.
Show the solution and common mistakes
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> counts;
    std::string word;
    while (std::cin >> word) {
        counts[word]++;
    }
    std::string best;
    int highest = 0;
    for (const auto& [w, n] : counts) {
        if (n > highest) {
            best = w;
            highest = n;
        }
    }
    if (highest == 0) {
        std::cout << "No words\n";
    } else {
        std::cout << best << " (" << highest << " times)\n";
    }
    return 0;
}
the code is short but the code is clear and the code compiles
code (3 times)

Here, "code" and "the" both appear 3 times: "code" wins, because it comes first in alphabetical order.

Common mistakes:

  • Using >= in the comparison: in case of a tie, the last word in alphabetical order would be kept.
  • Forgetting the case where no word is entered: the program would display an empty line and a count of 0.

Summary

  1. 1std::map<Key, Value> associates unique keys with values and keeps them sorted.
  2. 2m[key] reads or creates; contains, find and at let you read without creating.
  3. 3for (const auto& [key, value] : m) goes through the pairs in key order.
  4. 4std::sort, std::find and std::count_if (from <algorithm>) work between begin() and end().
  5. 5A lambda [](parameters) { … } customises an algorithm on the spot.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.