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.
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)
std::ranges::minmax_element()
, allowing the algorithm to compare Player
objects based on their Health
.std::ranges::minmax_element()
is a pair of iterators, minIt
and maxIt
, which point to the elements with the minimum and maximum health, respectively.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.
Answers to questions are automatically generated and may not have been reviewed.
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()
.