SyntaxPilot
Courses/C++/Lesson 30
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ · Lesson 30 of 40

Lambdas

queued

These are the notes for C++ episode 30. In episode 27 the algorithm library (sort, count_if, find_if) did the hard work for you, but each algorithm needs a rule: how to compare, what to count. This episode shows why a normal function is a clumsy way to hand over that rule, and invents the fix: a function written right where you need it, a lambda. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; outputs and error messages are copied from those runs.

All the examples use a class of four report cards:

struct Student { string name; int marks; };
vector<Student> cls = {{"Asha", 82}, {"Ravi", 67},
                       {"Neha", 91}, {"Kabir", 45}};

The problem: sort needs a rule

sort puts things in order using <. For a Student there is no <, and anyway you want the topper first. You must tell sort how to compare two students: a function that gets a and b and returns true if a should come first. The usual way is a separate named function:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

bool byMarks(const Student& a, const Student& b) {
    return a.marks > b.marks;                  // a goes first?
}

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67},
                           {"Neha", 91}, {"Kabir", 45}};
    sort(cls.begin(), cls.end(), byMarks);     // highest first
    for (const auto& s : cls)
        cout << s.name << " " << s.marks << endl;
    return 0;
}

Output:

Neha 91
Asha 82
Ravi 67
Kabir 45

It works, but the rule lives far away from the sort, under a name nobody else will call. Sort by name, by marks going up, by age: each is another tiny one-use function.

Then it breaks: the rule needs a value from main

How many students passed? The pass mark is typed in at run time, so it lives in main:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

bool passed(const Student& s) {
    return s.marks >= cutoff;         // which cutoff?
}

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67},
                           {"Neha", 91}, {"Kabir", 45}};
    int cutoff;
    cin >> cutoff;                         // pass mark, typed in
    int n = count_if(cls.begin(), cls.end(), passed);
    cout << n << " passed" << endl;
    return 0;
}

Compiler output:

main.cpp:10:23: error: 'cutoff' was not declared in this scope

A function only sees its own parameters and global variables. cutoff is a local variable of main. And count_if decides how passed is called (with one student, nothing else), so there's no way to hand it the pass mark.

Step 1: a sticky note, written on the spot

In the staff room In C++
A rule in the school handbook, written once, far away a named function, defined outside main
A sticky note for a helper, written on the spot a lambda, written inside the call
The number written on the note: "above 60" the capture list: [cutoff]

Step 2: a lambda, piece by piece

[cutoff] (const Student& s) { return s.marks >= cutoff; }
//  ^ capture     ^ parameters        ^ body
Part Meaning
[ ] capture list what the lambda takes along from the code around it; [] also tells C++ "a lambda starts here"
( ) parameters exactly like a normal function's parameters
{ } body the code; the return type is worked out by the compiler (here bool)

A lambda has no name. You can pass it straight to an algorithm, or store it in a variable with auto.

The lambda inside sort

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67},
                           {"Neha", 91}, {"Kabir", 45}};
    sort(cls.begin(), cls.end(),
         [](const Student& a, const Student& b) {
             return a.marks > b.marks;
         });
    for (const auto& s : cls)
        cout << s.name << " " << s.marks << endl;
    return 0;
}

Output:

Neha 91
Asha 82
Ravi 67
Kabir 45

The }); at the end looks odd at first: } ends the lambda, ) ends the sort call, ; ends the statement.

Step 3: capturing variables

Without a capture, a lambda can't see main's variables either:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67},
                           {"Neha", 91}, {"Kabir", 45}};
    int cutoff;
    cin >> cutoff;
    int n = count_if(cls.begin(), cls.end(),
                     [](const Student& s) {
                         return s.marks >= cutoff;
                     });
    cout << n << " passed" << endl;
    return 0;
}

Compiler output:

main.cpp:16:44: error: 'cutoff' is not captured

Put cutoff in the square brackets:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67},
                           {"Neha", 91}, {"Kabir", 45}};
    int cutoff;
    cin >> cutoff;
    int n = count_if(cls.begin(), cls.end(),
                     [cutoff](const Student& s) {
                         return s.marks >= cutoff;
                     });
    cout << n << " passed" << endl;
    return 0;
}

Input: 60

Output:

3 passed

Asha (82), Ravi (67) and Neha (91) have at least 60.

By value is read-only, by reference changes the real variable

Count how many comparisons sort makes. Capturing calls by value makes a copy, and that copy is read-only inside the lambda:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67},
                           {"Neha", 91}, {"Kabir", 45}};
    int calls = 0;
    sort(cls.begin(), cls.end(),
         [calls](const Student& a, const Student& b) {
             calls++;                 // count each comparison
             return a.marks > b.marks;
         });
    cout << "sort compared " << calls << " times" << endl;
    return 0;
}

Compiler output:

main.cpp:15:14: error: increment of read-only variable 'calls'

Capture it by reference with &:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67},
                           {"Neha", 91}, {"Kabir", 45}};
    int calls = 0;
    sort(cls.begin(), cls.end(),
         [&calls](const Student& a, const Student& b) {
             calls++;                 // count each comparison
             return a.marks > b.marks;
         });
    cout << "sort compared " << calls << " times" << endl;
    return 0;
}

Output:

sort compared 5 times

Everything that can go in the brackets

Capture Meaning
[] nothing; the lambda uses only its parameters
[cutoff] a copy of cutoff, taken when the lambda is created; read-only
[&calls] the real calls, by reference; the lambda can change it
[=] copies of every local variable the lambda uses
[&] every local variable it uses, by reference
[=, &calls] copies of everything, except calls by reference
[this] inside a member function: use the object's members

Good habit: name what you capture ([cutoff], [&calls]) so a reader sees exactly what the lambda touches. If you really need to change a by-value copy inside the lambda, mark it mutable: [calls]() mutable { calls++; } (it changes only the lambda's own copy).

mutable: a lambda's own counter

#include <iostream>
using namespace std;

int main() {
    int cups = 0;
    auto order = [cups]() mutable {    // its own copy, now changeable
        cups++;
        return cups;
    };
    cout << order() << " " << order() << " " << order() << endl;
    cout << "cups in main: " << cups << endl;
    return 0;
}

Output:

1 2 3
cups in main: 0

mutable lets the lambda change its own copy of cups, and the lambda keeps that copy between calls. cups in main never changes.

A lambda is a value: keep it with auto

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67},
                           {"Neha", 91}, {"Kabir", 45}};
    auto topper = [](const Student& s) { return s.marks >= 80; };
    int n = count_if(cls.begin(), cls.end(), topper);
    cout << n << " toppers" << endl;
    auto it = find_if(cls.begin(), cls.end(), topper);
    cout << "first topper: " << it->name << endl;
    cout << "Kabir a topper? " << topper(cls[3]) << endl;
    return 0;
}

Output:

2 toppers
first topper: Asha
Kabir a topper? 0

One rule, written once, used with count_if, with find_if, and called directly with () (0 is how cout prints false).

The snapshot trap

#include <iostream>
using namespace std;

int main() {
    int price = 10;                          // chai: 10 rupees
    auto photo = [price]() { return price; };   // a copy, taken now
    auto board = [&price]() { return price; };  // looks at the board
    price = 15;                               // the price goes up
    cout << "photo of the menu: " << photo() << endl;
    cout << "the menu board:    " << board() << endl;
    return 0;
}

Output:

photo of the menu: 10
the menu board:    15

A copy is taken when the lambda is created, like a photo of the menu board. Use a copy when you want a snapshot, a reference when you want the latest value.

The reverse trap is a dangling reference: a lambda that captured a local variable by reference, used after that variable is gone:

auto makeCounter() {
    int total = 0;
    return [&total]() { return total; };   // total dies when makeCounter returns!
}

This compiles, but calling the returned lambda reads memory that no longer belongs to total (undefined behaviour). If the lambda outlives the variable, capture by copy: [total].

Step 4: storing lambdas, std::function

Every lambda has its own unnamed type, so auto is how you keep one in a variable. To keep different lambdas in one container, use std::function from <functional>: function<void()> holds anything you can call with no arguments that returns nothing. A chai shop's order buttons:

#include <iostream>
#include <string>
#include <map>
#include <functional>
using namespace std;

int main() {
    int bill = 0;
    map<string, function<void()>> button;
    button["chai"]   = [&bill]() { bill += 10; };
    button["coffee"] = [&bill]() { bill += 25; };
    button["clear"]  = [&bill]() { bill = 0; };
    string order;
    while (cin >> order) {
        if (button.count(order)) button[order]();   // press it
        else cout << "no button: " << order << endl;
    }
    cout << "bill: " << bill << " rupees" << endl;
    return 0;
}

Input: chai chai coffee samosa

Output:

no button: samosa
bill: 45 rupees

button[order]() looks up a lambda by name and calls it with (). Use auto for a single lambda (faster, no overhead); use std::function for menus, buttons, callbacks, anything that stores different callables in one place.

Step 5: generic lambdas

A parameter can be auto; the lambda then works for any type that supports what the body does (here +):

#include <iostream>
#include <string>
using namespace std;

int main() {
    auto twice = [](auto x) { return x + x; };   // any type with +
    cout << twice(21) << endl;
    cout << twice(2.5) << endl;
    cout << twice(string("chai ")) << endl;
    return 0;
}

Output:

42
5
chai chai 

A generic lambda is a tiny template (episode 20): the compiler writes one version per type you call it with.

Common mistakes (and the real g++ messages)

Mistake What happens Fix
Using a local variable you didn't capture error: 'cutoff' is not captured [cutoff](...) { ... }
Changing a variable captured by value error: increment of read-only variable 'calls' [&calls], or mutable if you want a private copy
A plain function reaching for main's local error: 'cutoff' was not declared in this scope a lambda with a capture
Returning a lambda that captured a local by reference compiles; dangling reference, undefined behaviour capture by copy
Expecting [x] to see later changes to x compiles; the lambda keeps the old value [&x]
Forgetting #include <functional> for std::function error: 'function' was not declared in this scope include <functional>

Mini project: a grade report with lambdas

Sort by marks (highest first), count the passes for a typed-in cutoff, find the first student below the cutoff, and give everyone 5 grace marks with for_each:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67}, {"Neha", 91}, {"Kabir", 45}, {"Meera", 58}};
    int cutoff;
    cin >> cutoff;

    sort(cls.begin(), cls.end(), [](const Student& a, const Student& b) {
        return a.marks > b.marks;
    });
    int passed = count_if(cls.begin(), cls.end(), [cutoff](const Student& s) {
        return s.marks >= cutoff;
    });
    auto firstFail = find_if(cls.begin(), cls.end(), [cutoff](const Student& s) {
        return s.marks < cutoff;
    });
    cout << "passed: " << passed << " of " << cls.size() << endl;
    if (firstFail != cls.end())
        cout << "highest below the cutoff: " << firstFail->name << endl;

    for_each(cls.begin(), cls.end(), [](Student& s) { s.marks += 5; });   // grace marks
    for (const auto& s : cls)
        cout << s.name << " " << s.marks << endl;
    return 0;
}

Input: 60

Output:

passed: 3 of 5
highest below the cutoff: Meera
Neha 96
Asha 87
Ravi 72
Meera 63
Kabir 50

Practice

  1. Sort the class by name (A to Z), then by marks going up, using lambdas.
  2. Count students whose marks are between two numbers typed in.
  3. Count how many comparisons sort makes for 100 numbers in reverse order.
  4. Build a calculator: map<string, function<int(int, int)>> with + - * /.
Solutions

Exercises 1 and 2:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

int main() {
    vector<Student> cls = {{"Asha", 82}, {"Ravi", 67}, {"Neha", 91}, {"Kabir", 45}};
    sort(cls.begin(), cls.end(), [](const Student& a, const Student& b) { return a.name < b.name; });
    for (const auto& s : cls) cout << s.name << " ";
    cout << endl;
    sort(cls.begin(), cls.end(), [](const Student& a, const Student& b) { return a.marks < b.marks; });
    for (const auto& s : cls) cout << s.marks << " ";
    cout << endl;
    int lo, hi;
    cin >> lo >> hi;
    int n = count_if(cls.begin(), cls.end(), [lo, hi](const Student& s) {
        return s.marks >= lo && s.marks <= hi;
    });
    cout << n << " between " << lo << " and " << hi << endl;
    return 0;
}

Input: 60 85

Output:

Asha Kabir Neha Ravi 
45 67 82 91 
2 between 60 and 85

Exercise 3:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v;
    for (int i = 100; i >= 1; i--) v.push_back(i);
    int calls = 0;
    sort(v.begin(), v.end(), [&calls](int a, int b) { calls++; return a < b; });
    cout << "sorted: " << (is_sorted(v.begin(), v.end()) ? "yes" : "no") << endl;
    cout << "comparisons: " << calls << endl;
    return 0;
}

Output:

sorted: yes
comparisons: 526

(The exact count depends on the library's sort algorithm; it is roughly n log n.)

Exercise 4:

#include <iostream>
#include <string>
#include <map>
#include <functional>
using namespace std;

int main() {
    map<string, function<int(int, int)>> calc = {
        {"+", [](int a, int b) { return a + b; }},
        {"-", [](int a, int b) { return a - b; }},
        {"*", [](int a, int b) { return a * b; }},
        {"/", [](int a, int b) { return b != 0 ? a / b : 0; }},
    };
    int a, b;
    string op;
    while (cin >> a >> op >> b) {
        if (calc.count(op)) cout << a << " " << op << " " << b << " = " << calc[op](a, b) << endl;
        else cout << "unknown operator " << op << endl;
    }
    return 0;
}

Input:

12 * 4
9 - 20
7 % 2

Output:

12 * 4 = 48
9 - 20 = -11
unknown operator %

Quick quiz

What does this print?

int x = 1;
auto a = [x]()  { return x; };
auto b = [&x]() { return x; };
x = 5;
cout << a() << b();
Answer

15. a copied x when it was created (1); b reads the real x, which is 5 by the time it's called.

Interview questions

  1. What is a lambda expression? An unnamed function object written inline: [capture](params) { body }. The compiler turns it into a small class with an operator().
  2. Capture by value vs by reference? [x] copies x when the lambda is created (read-only unless mutable); [&x] refers to the original, so it sees changes and can modify it, but can dangle.
  3. What does mutable do on a lambda? Lets the body modify its by-value copies (not the originals).
  4. What is the type of a lambda? A unique, unnamed closure type; store it with auto, or in std::function when you need one common type.
  5. std::function vs auto / templates? std::function can hold any callable with a given signature (type erasure) but has some overhead; auto and templates keep the exact type and can be inlined.
  6. What is a generic lambda? A lambda with auto parameters (C++14); it acts like a function template.
  7. Can a lambda with no captures be converted to a function pointer? Yes, a capture-less lambda converts to a plain function pointer.
  8. What is a dangling capture? Capturing a local by reference in a lambda that outlives it; using it is undefined behaviour.

Glossary

Term Meaning, with an example
comparator A function that says whether a goes before b: return a.marks > b.marks;
predicate A function that returns true/false for one item, used by count_if, find_if.
lambda (lambda expression) A function with no name, written where it's used: [](int x) { return x * 2; }
closure The object a lambda creates, holding its captured variables.
capture list The [ ] part: which outside variables the lambda takes along.
capture by value [cutoff]: the lambda keeps its own copy, taken when it is created.
capture by reference [&calls]: the lambda uses the original variable.
[=] / [&] Capture everything used, by value / by reference.
mutable Lets a lambda change its own by-value copies.
snapshot A by-value capture: later changes to the original are not seen.
dangling reference A reference to a variable that no longer exists.
scope Where a variable can be seen; main's locals are invisible to other functions.
std::function A type from <functional> that can hold any callable with a given signature: function<void()>.
callable Anything you can call with (): a function, a lambda, a std::function.
callback A function you hand to someone else to call later, like a button's action.
generic lambda A lambda with auto parameters: [](auto x) { return x + x; }
for_each An algorithm that calls a function on every element.

Summary

  • Algorithms like sort and count_if take a rule; a named function puts it far away and can't see main's variables.
  • A lambda [capture](params) { body } is written right where it's used.
  • [x] copies (read-only, a snapshot); [&x] uses the real variable (but can dangle); [=] and [&] capture everything used.
  • std::function stores any callable, e.g. a map of buttons; auto is enough for one lambda.
  • auto parameters make a generic lambda.

Next episode: a user types abc where you asked for an age, a payment fails deep inside your code. How does a function say "something went wrong"? Exceptions.