Lambdas

Using Lambdas as Comparators

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

Abstract art representing computer programming

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.

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