Searching with a Lambda: std::find_if
To find a monster by its name, std::find isn't enough. It compares whole elements, and a monster isn't the same as the string "Troll": std::find(monsters.begin(), monsters.end(), "Troll") ends with the error invalid operands to binary expression ('Monster' and 'const char[6]'). For such searches, there's std::find_if. Like std::count_if, it takes a lambda. It returns an iterator to the first element for which the lambda returns true, or end() when there's no such element:
std::string wanted = "Troll";
auto it = std::find_if(monsters.begin(), monsters.end(), [wanted](const Monster& monster) {
return monster.name == wanted;
});
if (it != monsters.end()) {
std::cout << (*it).name << " has " << (*it).health << " health" << std::endl;
}With the monsters in the editor, this prints Troll has 80 health. *it is the monster, and (*it).name is its name. The parentheses are needed, because the dot goes first: *it.name would look for a member name in the iterator itself. You need this so often that C++ has a shorter way to write it, the arrow ->. it->name means exactly the same as (*it).name:
if (it != monsters.end()) {
std::cout << it->name << " has " << it->health << " health" << std::endl;
}The arrow works the same way with pointers: after Monster* p = &monsters[0];, p->name is the name of the first monster. When you write a dot instead of the arrow, the compiler tells you what to do: error: no member named 'name' in 'std::__wrap_iter<Monster *>'; did you mean to use '->' instead of '.'?
Remember that std::find_if returns the first element that fits and doesn't look any further. If you look for a monster with more than 40 health, you get the Orc (50), even though the Troll comes later with 80.
Instructions
- 1
Find the monster whose name is in
wanted, withstd::find_ifand a lambda that captureswanted. When it's there, print its name, health and attack asTroll: health 80, attack 7. When it isn't, printNot found:and the name fromwanted. Keep the line withwantedas it is: the exercise also runs your program with other names. - 2
Below that, find the first monster in the vector with an attack of at least
8, and print its name asFirst strong one: Orc. Keep the monsters as they are.