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
- Start with Key A has value 2
- Do this Look up A
- Result 2
#include <iostream>
#include <map>
int main() {
std::map<char, int> counts{{'A', 2}};
std::cout << counts.at('A') << '\n';
}
2
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.
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
#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;
}
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.