Lambda Expressions in C++ 🎭
The Magic of Mini-Functions
Imagine you have a magic sticky note. Instead of writing a whole recipe book, you just write a tiny instruction on this note and hand it to someone. They do exactly what the note says, right there on the spot!
That’s what a lambda is in C++ — a tiny, nameless function you create exactly where you need it.
🌟 What is a Lambda Expression?
A lambda is like a secret helper that appears, does one job, and disappears.
The Basic Recipe
[capture](parameters) -> return_type {
// body
}
Think of it like this:
| Part | What It Means |
|---|---|
[ ] |
What you bring from outside |
( ) |
What you give it to work with |
{ } |
What it does |
Your First Lambda
auto sayHello = []() {
cout << "Hello!";
};
sayHello(); // Prints: Hello!
Translation: “Create a helper called sayHello. It needs nothing from outside, takes no inputs, and just says Hello!”
🎒 Lambda Capture Modes
Here’s where the magic gets interesting! The [ ] part is called the capture clause. It’s like deciding what supplies to pack in your backpack before a trip.
The Empty Backpack []
int x = 10;
auto noCapture = []() {
// Can't use x here!
};
You brought nothing. You can only use what’s given directly.
Capture by Value [=]
int cookies = 5;
auto countCookies = [=]() {
cout << cookies; // Shows 5
};
cookies = 10;
countCookies(); // Still shows 5!
Story: You took a photo of the cookie jar when you left. Even if someone adds more cookies later, your photo still shows 5.
Capture by Reference [&]
int score = 0;
auto addPoint = [&]() {
score++; // Actually changes score!
};
addPoint();
cout << score; // Shows 1
Story: You have a walkie-talkie connected to home. When you say “add a point,” it really happens back at the scoreboard!
Capture Specific Variables
int a = 1, b = 2, c = 3;
// Only take 'a' by value
auto f1 = [a]() { return a; };
// Only take 'b' by reference
auto f2 = [&b]() { b++; };
// Mix and match!
auto f3 = [a, &b]() {
// 'a' is a copy
// 'b' is the real one
};
The Capture Cheat Sheet
graph TD A["[ ]"] --> B[Nothing captured] C["[=]"] --> D[All by value - photos] E["[&]"] --> F[All by reference - live link] G["[x]"] --> H[Just x by value] I["[&x]"] --> J[Just x by reference] K["[=, &x]"] --> L[All by value, x by reference] M["[&, x]"] --> N[All by reference, x by value]
🔧 Generic Lambdas (C++14+)
What if your helper could work with anything — numbers, words, even dragons?
The auto Superpower
auto add = [](auto a, auto b) {
return a + b;
};
cout << add(3, 4); // 7
cout << add(1.5, 2.5); // 4.0
cout << add("Hi", "!"); // Error for strings
Story: Instead of saying “I need exactly 2 apples,” you say “I need 2 things.” Now you can work with apples, oranges, or toys!
Real Example
auto printTwice = [](auto x) {
cout << x << " " << x;
};
printTwice(42); // 42 42
printTwice("wow"); // wow wow
printTwice(3.14); // 3.14 3.14
🎯 Putting It All Together
Example: Sorting with Lambdas
vector<int> nums = {5, 2, 8, 1};
// Sort smallest to largest
sort(nums.begin(), nums.end(),
[](int a, int b) {
return a < b;
}
);
// nums is now {1, 2, 5, 8}
Example: Capture and Modify
int total = 0;
vector<int> prices = {10, 20, 30};
for_each(prices.begin(), prices.end(),
[&total](int price) {
total += price;
}
);
cout << total; // 60
🧠 Quick Summary
| What | Syntax | When to Use |
|---|---|---|
| Basic Lambda | [](){} |
Simple one-time tasks |
| Capture Value | [=] or [x] |
Need a snapshot |
| Capture Reference | [&] or [&x] |
Need to modify original |
| Generic Lambda | [](auto x) |
Work with any type |
🚀 Why Lambdas Are Amazing
- No Name Needed — Use it once, forget it
- Right Where You Need It — No jumping to another file
- Captures Context — Brings variables along for the ride
- Works with STL — Perfect for
sort,find_if, etc.
🎪 One Last Story
Think of lambdas like street performers:
- They appear exactly where needed
- They carry their props (captures)
- They perform one act (the body)
- They disappear when done
You don’t need to build a whole theater (regular function) for a quick magic trick!
You now understand lambdas! They’re just tiny, portable functions that can bring their own supplies and work with anything. Go create some magic! ✨