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.
An introduction to lambda expressions - a concise way of defining simple, ad-hoc functions