Counting: std::count_if
In the Loops lesson, you counted with a counter, a loop and an if:
std::vector<int> scores = {640, 1250, 380, 980, 720};
int over700 = 0;
for (int score : scores) {
if (score > 700) {
over700++;
}
}The algorithm std::count_if does all of this in one line:
int over700 = std::count_if(scores.begin(), scores.end(), [](int score) { return score > 700; });Both versions give 3: the scores 1250, 980 and 720. Look at what's left of the loop. The condition of the if, score > 700, is now the body of a lambda. std::count_if calls the lambda for each element of the range and counts the elements for which it returns true. The counter, the loop and the ++ are its job.
This lambda has one parameter, because it answers a question about one element: “Is this score over 700?” The lambda for std::sort has two, because it compares two elements. With the wrong number of parameters, the program doesn't compile.
With structs, the lambda gets the whole struct and can look at any of its members. This counts the monsters with an attack of at least 5:
int strong = std::count_if(monsters.begin(), monsters.end(), [](const Monster& monster) {
return monster.attack >= 5;
});For the five monsters of the previous exercises, strong is 3: the Goblin, the Orc and the Troll.
When you only want to count the elements that are equal to a value, you don't need a lambda. std::count takes the value itself:
std::vector<std::string> loot = {"gold", "potion", "gold", "bone", "gold"};
int gold = std::count(loot.begin(), loot.end(), "gold");Here, gold is 3.
Instructions
- 1
The vector
lootholds what the hero found after a fight. Count withstd::counthow many times"potion"is in it, and print the result asPotions: 2. Keep the line with the loot as it is: the exercise also runs your program with other loot. - 2
After the fight, some of the monsters have
0health left. Count withstd::count_ifand a lambda the monsters that are still alive, the ones with more than0health, and print the result asStill alive: 2. Keep the monsters as they are.