Lambdas

# 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.

This Question is from the Lesson:

### Lambdas

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

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

This Question is from the Lesson:

### Lambdas

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

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.