Counting with a Map
That square brackets add a missing key with 0 makes counting easy. Say the monsters in the arena dropped this loot, and you want to know how many of each thing there are:
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::vector<std::string> loot = {"gem", "potion", "gem", "bread", "gem", "potion"};
std::map<std::string, int> counts;
for (const std::string& item : loot) {
counts[item]++;
}
for (const auto& [item, count] : counts) {
std::cout << item << ": " << count << std::endl;
}
return 0;
}This prints:
bread: 1
gem: 3
potion: 2The first time the loop meets "gem", the key isn't in counts yet. counts["gem"] adds it with 0, and ++ makes it 1. The next time, ++ turns the 1 into 2, and so on. The other things are counted the same way, each under its own key.
In the Loops lesson, you counted with a variable of your own, count++ inside an if. That works when you know beforehand what you count. For ten kinds of loot, you would need ten variables and ten conditions, and for a kind you didn't think of, nothing would count it. The map makes a new counter for every new key by itself, and the one line counts[item]++; counts them all.
When the loop over counts prints the result, the things come out sorted, whatever order they were found in.
Instructions
- 1
Count how many monsters of each kind Aria defeated: create a map
countsand count the names indefeated, as in the example. Then print each monster with its number, one line each:Orc: 2 Slime: 3 Troll: 1Keep the line with
defeatedas it is: the exercise will also try other fights. - 2
Below, print the monster Aria defeated most often, with its number:
Most often: Slime (3). Look for it the way you looked for the largest value in the Loops lesson: go through the map, and keep the name and the number of the best monster so far.