Yes or No: std::any_of and std::all_of
Sometimes you don't need a number, only a yes or a no about the whole vector. Is any monster still alive? Are all of them defeated? With a loop, you would need a bool variable, an if and maybe break. The algorithms std::any_of, std::all_of and std::none_of answer such questions directly. Each of them takes a lambda that asks about one element, as std::count_if does, and returns true or false:
std::any_of: is the lambda true for at least one element?std::all_of: is it true for every element?std::none_of: is it true for no element at all?
The result is a bool, which you can store in a variable and use as a condition:
bool allDefeated = std::all_of(monsters.begin(), monsters.end(), [](const Monster& monster) {
return monster.health == 0;
});
if (allDefeated) {
std::cout << "Victory!" << std::endl;
}These algorithms stop as soon as they know the answer, like a loop with break. std::any_of stops at the first element for which the lambda returns true, and std::all_of at the first one for which it returns false.
A question can often be asked in two ways. “Are all the monsters defeated?” means the same as “Is none of them alive?”, so std::none_of with monster.health > 0 gives the same answer as the example. Choose the one that reads most like your question.
One surprise: for an empty vector, std::all_of returns true, because it has no element for which the lambda would be false. std::any_of returns false, because it has no element at all.
Instructions
- 1
When all the monsters have
0health, the fight is won. Check it withstd::all_of, and printVictory!when it's true, orThe fight goes onwhen it isn't. Keep the monsters as they are: the exercise also runs your program with other values. - 2
The hero is in danger when a monster that is still alive could take all of the hero's health with one blow: its health is more than
0, and its attack is at leastheroHealth. Check it withstd::any_ofand a lambda that capturesheroHealth. PrintDanger!when it's true, orSafe for nowwhen it isn't. Keep the line withheroHealthas it is.