Code Snippets
/

C++ Lambda Basics

C++ Lambda Basics

Lambdas (C++11+) are first-class anonymous function objects with a compact syntax: `[capture](params) { body }`. This snippet covers the basic form, the difference between by-value `[=]` and by-reference `[&]` captures, and using lambdas with standard algorithms like `std::sort` and `std::for_each`. Reach for them anywhere you would write a small functor or pass a callback.

C++
Easy
3 snippets
cpp-lambdas
functional-programming
cpp-stl

213 views

3

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

int main() {
    auto add = [](int a, int b) { return a + b; };
    std::cout << "3+4=" << add(3, 4) << "\n";

    std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
    int sum = std::accumulate(v.begin(), v.end(), 0,
                              [](int acc, int x) { return acc + x; });
    std::cout << "sum=" << sum << "\n";
    return 0;
}

The square brackets are the capture clause; the parentheses are the parameter list; the braces are the body. The compiler synthesises a closure type with operator(), so the lambda is callable like any function object. auto add = [](int, int) { ... }; stores it in a variable; passing it inline to algorithms is more common. The return type is deduced; you can specify it explicitly with -> int after the parameter list when deduction would be ambiguous.