C++ Lambda Functions

🧩 C++ Lambda Functions

Lambda functions in C++ are anonymous (unnamed) functions that you can define inline.
They are especially useful for short operations, callbacks, and STL algorithms.

Introduced in C++11.


πŸ”Ή 1. Basic Syntax

[capture](parameters) -> return_type {
// function body
};
  • capture β†’ variables from outside the lambda

  • parameters β†’ function parameters

  • return_type β†’ optional (often auto-deduced)


πŸ”Ή 2. Simple Lambda Example

auto greet = []() {
cout << "Hello, Lambda!";
};
greet();


πŸ”Ή 3. Lambda with Parameters

auto add = [](int a, int b) {
return a + b;
};
cout << add(10, 20); // 30


πŸ”Ή 4. Lambda with Explicit Return Type

auto divide = [](int a, int b) -> double {
return (double)a / b;
};
cout << divide(10, 3);


πŸ”Ή 5. Capture Variables (Very Important)

Capture by Value [=]

int x = 10;

auto show = [=]() {
cout << x;
};

show();

βœ” Read-only copy inside lambda


Capture by Reference [&]

int x = 10;

auto modify = [&]() {
x = 20;
};

modify();
cout << x; // 20


Capture Specific Variables

int a = 5, b = 10;

auto sum = [a, &b]() {
b = 20;
return a + b;
};


πŸ”Ή 6. Lambda in STL Algorithms (Very Common)

Example: for_each

#include <vector>
#include <algorithm>
vector<int> v = {1, 2, 3, 4};

for_each(v.begin(), v.end(), [](int x) {
cout << x << ” “;
});


Example: sort

sort(v.begin(), v.end(), [](int a, int b) {
return a > b; // descending order
});

πŸ”Ή 7. Lambda with mutable

Allows modification of captured-by-value variables.

int x = 10;

auto func = [x]() mutable {
x += 5;
cout << x;
};

func();
cout << x; // still 10


πŸ”Ή 8. Lambda as Function Argument

void operate(int a, int b, auto func) {
cout << func(a, b);
}
operate(5, 3, [](int x, int y) {
return x * y;
});


πŸ”Ή 9. Lambda vs Normal Function

Lambda Normal Function
Inline & short Separate definition
Can capture variables Cannot capture
Common with STL General purpose
Anonymous Named

❌ Common Mistakes

int x = 10;

auto f = []() {
cout << x; // ❌ x not captured
};

βœ” Correct:

auto f = [x]() {
cout << x;
};

πŸ“Œ Summary

  • Lambda = anonymous inline function

  • Syntax: [capture](params){}

  • Can capture variables by value or reference

  • Widely used with STL algorithms

  • Makes code concise and expressive

You may also like...