Step 2 of 6
Lambdas
Many algorithms let you customize them by passing a function. The easiest way to write that function is a lambda: an unnamed function written right where you need it.
auto square = [](int x) { return x * x; };
square(5); // 25
[]is the capture list (more soon)(int x)are the parameters- the body is in
{ }, and the return type is deduced from thereturn
std::sort takes an optional third argument, a comparison: given two elements a and b, return true if a should come before b.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Player {
std::string name;
int score;
};
int main() {
std::vector<Player> team = {{"ana", 40}, {"bo", 75}, {"cy", 40}, {"di", 90}};
std::sort(team.begin(), team.end(), [](const Player& a, const Player& b) {
if (a.score != b.score) return a.score > b.score; // higher score first
return a.name < b.name; // ties: alphabetical
});
for (const auto& p : team) std::cout << p.name << ":" << p.score << " ";
std::cout << "\n";
auto is_vowel = [](char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; };
std::cout << is_vowel('e') << is_vowel('z') << "\n";
}
di:90 bo:75 ana:40 cy:40
10
Writing a comparison
a < bgives ascending order;a > bgives descending.- To sort by something else, compare that thing:
a.score > b.score,a.size() < b.size(). - For ties, compare a second field, as the example does with names.
- Take the parameters by
const&, so sorting strings or structs doesn't copy them on every comparison.
Common mistakes
- Using
<=instead of<. The comparison must returnfalsefor equal elements;<=breaks that rule and can makestd::sortmisbehave or crash. - Forgetting the
return. A lambda body with noreturnreturns nothing, and the compiler will complain thatvoidcan't be used as a bool.
Your turn: sort the words by length, shortest first.