The Largest Element: std::max_element
Finding the largest value was a pattern of the Loops lesson too. In <algorithm>, it's std::max_element, and std::min_element finds the smallest value. Like std::find, they return an iterator, so you get the value with * and the index by subtracting begin():
std::vector<int> scores = {640, 1250, 380, 980, 720};
auto best = std::max_element(scores.begin(), scores.end());
auto worst = std::min_element(scores.begin(), scores.end());
std::cout << "Best: " << *best << " at index " << best - scores.begin() << std::endl;
std::cout << "Worst: " << *worst << std::endl;This prints:
Best: 1250 at index 1
Worst: 380When several elements are equally large, std::max_element returns the first of them. For an empty vector, both algorithms return end(), so use * on the result only when the vector has elements.
For monsters, you need a lambda again, one with two parameters, as for std::sort. It answers the same question: does a come before b, that is, is a smaller than b? The largest element is the one that would come last:
auto strongest = std::max_element(monsters.begin(), monsters.end(), [](const Monster& a, const Monster& b) {
return a.attack < b.attack;
});
std::cout << "Strongest: " << strongest->name << std::endl;With the monsters in the editor, this prints Strongest: Dragon. Watch the sign: the lambda compares with <, even though you're looking for the largest attack. With >, “smaller” would mean “stronger”, and std::max_element would return the weakest monster, the Slime.
Don't confuse these algorithms with std::max(a, b) and std::min(a, b), which take two values and return the larger or the smaller one. They come in handy too: health = std::max(0, health - 30); takes 30 health away, but never goes below zero.
Instructions
- 1
The vector
scoresholds the scores of five players. Find the highest score withstd::max_elementand print it with the number of the player who has it, which is one more than its index:Best score: 1250 (player 2). Keep the line with the scores as it is: the exercise also runs your program with other values. - 2
Find the monster with the least health with
std::min_elementand a lambda, and print its name:Weakest: Bat. Keep the monsters as they are. - 3
Find the monster with the highest attack with
std::max_element, and print its name and its attack:Strongest: Dragon (25).