C/C++ Arena

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

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

Common mistakes

Your turn: sort the words by length, shortest first.

Previous: sort and reverse Next: find_if, count_if, any_of