Lesson contents

C++ — Counting values with vector and map

In C++, std::map can associate each distinct string with an integer count. Indexing a missing key in a map of integers starts its count at zero.

A simple example

Look up one count

  1. Start with Key A has value 2
  2. Do this Look up A
  3. Result 2
The key identifies which stored value to read.
lesson.cpp
#include <iostream>
#include <map>

int main() {
    std::map<char, int> counts{{'A', 2}};
    std::cout << counts.at('A') << '\n';
}
Output
2
Advertisements

Count labels without relying on storage order

The map stores one counter per distinct string. Indexing a missing key constructs an int initialized to zero. Later, at accesses a key known to exist without inserting one.

Scan order: Red, blue, red. Red team: 2 wristbands. Blue team: 1 wristband.
Count team wristbands

A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.

Run the example

C++17. Run these commands from the directory containing the example. Use a Unix-style shell.

c++ -std=c++17 lesson.cpp -o lesson
./lesson
lesson.cpp
#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    const std::vector<std::string> colors{"red", "blue", "red"};
    std::map<std::string, int> counts;
    for (const auto& color : colors) ++counts[color];
    for (const auto& color : {"red", "blue"}) {
        std::cout << color << ' ' << counts.at(color) << '\n';
    }
    return 0;
}
Output
red 2
blue 1

The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.

Try it yourself

Insert another blue before the last red. What changes?

Check your answer

Both keys now have a count of two. The requested display order stays red, then blue.

C++ language and library reference

Related tags

  • C++
  • collections
  • frequency counts
  • lookup