Using Lambdas as Comparators

Can I use a lambda as a comparator for STL containers and algorithms?

Yes, lambdas are often used as comparators for STL containers and algorithms. This is because lambdas provide a concise way to define a comparison operation right where it's needed.

For example, let's say you have a std::vector of Player objects, each of which has a score member. You can sort this vector based on the scores using std::sort and a lambda comparator:

#include <iostream>
#include <vector>
#include <algorithm>

struct Player {
  std::string name;
  int score;
};

int main() {
  std::vector<Player> players {
    {"Alice", 30},
    {"Bob", 50},
    {"Charlie", 40}
  };

  std::sort(players.begin(), players.end(),
    [](const Player& a, const Player& b) {
      return a.score < b.score;
    });

  for (const auto& player : players) {
    std::cout << player.name << ": "
      << player.score << '\n';
  }
}
Alice: 30
Charlie: 40
Bob: 50

Here, std::sort is called with three arguments: the start of the range to sort, the end of the range, and a comparator.

The comparator is a lambda that takes two Player objects and returns true if the first player's score is less than the second player's score. This lambda will be called by std::sort to determine the order of the elements.

This same technique can be used with other algorithms and containers in the STL. For example, you could use a lambda comparator with std::set or std::map to specify a custom ordering for the elements.

Using lambdas as comparators is often preferable to defining a separate named comparator function, as it keeps the comparison logic right where it's used and avoids cluttering the global namespace.

Lambdas

An introduction to lambda expressions - a concise way of defining simple, ad-hoc functions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Capturing Class Members in Lambdas
How can I capture member variables of a class when defining a lambda inside a member function?
Returning Lambdas from Functions
Can I return a lambda from a function? If so, how do I specify the return type?
Using Lambdas in Template Functions
How can I pass a lambda as an argument to a function template?
Creating Stateful Lambdas
Is it possible to create a lambda that maintains state across multiple invocations?
Creating Recursive Lambdas
Can a lambda call itself recursively?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant