Codiqo

Learn C++ · lesson 54 of 61 · about 8 minutes

Lambdas

Write a small function right where you need it, and store it in a variable.

What you'll learn

  • Read and write lambda syntax
  • Store a lambda in an auto variable and call it
  • Pass a lambda to an algorithm

The spell book

At the top of the tower the hero finds a spell book. The player types the spells the hero knows, like fire zap frost ice lightning, until done, and the adventure lists them quickest first, which means shortest, because a short spell is quicker to say: Spells, quickest first: zap ice fire frost lightning. Then the hero casts the quickest one out loud, in capitals: The hero casts ZAP!. Both jobs need a small function written right where it's used.

A function without a name

You've already passed small functions like [](int x) { return x >= 50; } to count_if. That's a lambda: a function with no name, written where it's used.

  • [] starts it (the brackets can capture outside variables; more on that next lesson)
  • (int x) is the parameter list, like any function
  • { return ...; } is the body

You can also keep a lambda in a variable with auto and call it like a normal function.

Storing and calling lambdas

#include <iostream>
#include <string>

int main() {
    auto square = [](int x) { return x * x; };
    auto greet = [](const std::string& name) { return "Hi, " + name + "!"; };
    std::cout << square(7) << "\n";
    std::cout << greet("Ada") << "\n";
}

Output

49
Hi, Ada!

Telling algorithms what to do

Many algorithms take a lambda that decides something. std::sort takes one that says whether a should come before b, so you can sort in any order you like: by length, backwards, or by a field of a struct.

Sorting by length

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words = {"banana", "fig", "kiwi", "cherry"};
    std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) {
        return a.size() < b.size();
    });
    for (const auto& w : words) std::cout << w << " ";
    std::cout << "\n";
}

Output

fig kiwi banana cherry

Keeping ties in order

zap and ice are both 3 letters, so the lambda says neither comes first. std::sort may put them either way round, but std::stable_sort keeps items that tie in the order they were typed, so zap stays before ice. A lambda kept in a variable, like auto quicker = ..., can be handed to stable_sort by name, and loud(spellBook[0]) calls the other stored lambda just like a function.

Tip

A sort lambda must answer "should a come before b?" with true or false. Use <, not <=, or sort can misbehave.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.