Minimum and Maximum Algorithms

Using minmax_element() with a lambda

How can I use minmax_element() with a lambda function for comparison?

Abstract art representing computer programming

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 {
  Player(std::string Name, int Health)
      : Name(Name), Health(Health) {}

  std::string GetName() const { return Name; }
  int GetHealth() const { return Health; }

  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)


  • Custom Comparison: The lambda function is passed to std::ranges::minmax_element(), allowing the algorithm to compare Player objects based on their Health.
  • Structured Binding: The result of std::ranges::minmax_element() is a pair of iterators, minIt and maxIt, 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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved