Lambdas: Quick Little Functions

A lambda is a small function without a name that you can write right where you need it. The shape is: [ ](parameters) { body }

#include <iostream>
using namespace std;

int main() {
    auto square = [](int x) {
        return x * x;
    };
    auto greet = []() {
        cout << "Hi from a lambda!\n";
    };
    cout << square(7) << "\n";
    greet();
    return 0;
}

Output

49
Hi from a lambda!

Capturing variables: [ ]

The square brackets say which outside variables the lambda may use. [limit] copies limit in; [&total] uses the real total so the lambda can change it:

#include <iostream>
using namespace std;

int main() {
    int limit = 10;
    auto isBig = [limit](int x) { return x > limit; };
    cout << boolalpha << isBig(5) << " " << isBig(50) << "\n";

    int total = 0;
    auto add = [&total](int x) { total += x; };
    add(5);
    add(20);
    cout << "Total: " << total << "\n";
    return 0;
}

Output

false true
Total: 25
CaptureMeans
[]use no outside variables
[x]a copy of x
[&x]the real x (by reference)
[=]copies of everything it uses
[&]everything it uses, by reference

Storing a lambda: function

To keep a lambda in a container or pass it around, use function from <functional>. function<int(int, int)> means “a function taking two ints and returning an int”:

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

int main() {
    map<string, function<int(int, int)>> ops = {
        {"add", [](int a, int b) { return a + b; }},
        {"mul", [](int a, int b) { return a * b; }},
    };
    cout << ops["add"](6, 7) << " " << ops["mul"](6, 7) << "\n";
    return 0;
}

Output

13 42
HOME LABS COMMUNITY DASHBOARD