Using minmax_element()
with a lambda
How can I use minmax_element()
with a lambda function for comparison?
You can use std::ranges::minmax_element()
with a lambda function to customize the comparison logic. This is useful when you need to determine the minimum and maximum elements based on a specific criterion.
Example Scenario
Consider a Player
class where each player has a Health
attribute. We want to find the players with the minimum and maximum health using a lambda function.
Step 1: Define the Custom Type
#include <algorithm>
#include <iostream>
#include <vector>
class Player {
public:
Player(std::string Name, int Health)
: Name(Name), Health(Health) {}
std::string GetName() const { return Name; }
int GetHealth() const { return Health; }
private:
std::string Name;
int Health;
};
Step 2: Use std::ranges::minmax_element()
with Lambda
#include <algorithm>
#include <iostream>
#include <vector>
class Player {/*...*/};
int main() {
std::vector<Player> Party {
Player("Roderick", 100),
Player("Anna", 200),
Player("Robert", 500)
};
auto [minIt, maxIt] = std::ranges::minmax_element(
Party,
[](const Player& a, const Player& b) {
return a.GetHealth() < b.GetHealth();
}
);
std::cout << "Player with the least health: "
<< minIt->GetName() << " ("
<< minIt->GetHealth() << ")\n";
std::cout << "Player with the most health: "
<< maxIt->GetName() << " ("
<< maxIt->GetHealth() << ")\n";
}
Player with the least health: Roderick (100)
Player with the most health: Robert (500)
Explanation
- Custom Comparison: The lambda function is passed to
std::ranges::minmax_element()
, allowing the algorithm to comparePlayer
objects based on theirHealth
. - Structured Binding: The result of
std::ranges::minmax_element()
is a pair of iterators,minIt
andmaxIt
, which point to the elements with the minimum and maximum health, respectively. - Output: The program prints the names and health of the players with the minimum and maximum health.
Using a lambda function with std::ranges::minmax_element()
provides a flexible way to customize the comparison logic, enabling you to handle complex scenarios with ease.
Minimum and Maximum Algorithms
An introduction to the seven minimum and maximum algorithms in the C++ standard library: clamp()
, min()
, min_element()
, max()
, max_element()
, minmax()
, and minmax_element()
.