CODE: CPP Lambda function

Lambdas in C++ are anonymous function objects that enable functional programming patterns such as higher-order functions, immutability, and expressive STL usage.They are zero-cost abstractions built on top of operator(), evolving naturally from functors into modern C++ functional style.

Lambdas are one of the most important features introduced in C++11, transforming C++ into a modern, expressive, multi-paradigm language.

What Is a Lambda?

A lambda is:

An anonymous function object (anonymous functor).

It is syntactic sugar for a class with operator().

Compiler transformation (conceptually):

cpp
auto add = [](int a, int b){ return a + b; };

Becomes something like:

cpp
class __Lambda {
public:
    int operator()(int a, int b) const {
        return a + b;
    }
};

__Lambda add;


Lambda Syntax Breakdown

md
[capture](parameters) -> return_type {
    body
};

Example:

cpp
auto multiply = [](int x, int y) -> int {
    return x * y;
};

Most of the time, return type is deduced:

cpp
auto multiply = [](int x, int y) {
    return x * y;
};


The Capture List

The capture list allows lambdas to access external variables.

md
[ ]   → capture nothing
[=]   → capture everything by value
[&]   → capture everything by reference
[x]   → capture x by value
[&x]  → capture x by reference

Example:

cpp
int factor = 5;

auto scale = [factor](int x) {
    return x * factor;
};

By Value

cpp
int x = 10;

auto f = [x]() {
    return x + 5;
};

x = 20;
std::cout << f();  // 15

Captured copy does not change.

By Reference

cpp
int x = 10;

auto f = [&x]() {
    return x + 5;
};

x = 20;
std::cout << f();  // 25


Mutable Lambdas

By default, lambdas are const.

To modify captured-by-value variables:

cpp
int x = 10;

auto f = [x]() mutable {
    x += 5;
    return x;
};

mutable removes const from operator().


Generic Lambdas (C++14)

Templates without writing templates.

cpp
auto add = [](auto a, auto b) {
    return a + b;
};

Works for:

md
int
double
std::string
custom types with operator+


Lambdas and STL

Modern STL heavily relies on lambdas.

Example:

cpp
#include <algorithm>
#include <vector>

std::vector<int> v = {1, 2, 3, 4};

std::sort(v.begin(), v.end(), [](int a, int b) {
    return a > b;
});

Before C++11, you'd need a functor class.


When to Use Lambdas

Use lambdas when:

✔ Short inline logic

✔ STL algorithm customization

✔ Local transformation logic

✔ Higher-order function usage

✔ Avoiding unnecessary class definitions

Avoid lambdas when:

✖ Large complex logic

✖ Reusable public API components

✖ When named type improves clarity