🔹 C++ Lambda Expressions – Tiny Functions on the Fly
Imagine writing a quick function without leaving your spot in the code. That’s exactly what lambda expressions let you do!
They’re short, powerful, and super handy for one-time use – like passing a function into another function! 🎯
📌 Basic Syntax
[capture] (parameters) { body }
- capture: What variables to grab from the surrounding scope
- parameters: Like a normal function’s input
- body: What the lambda should do
🧪 Example: Simple Lambda
#include <iostream>
using namespace std;
int main() {
auto sayHello = []() {
cout << "Hello from a lambda!" << endl;
};
sayHello(); // Call the lambda
return 0;
}
🔢 Example: Lambda with Parameters
#include <iostream>
using namespace std;
int main() {
auto add = [](int a, int b) {
return a + b;
};
cout << "Sum: " << add(3, 4) << endl;
return 0;
}
🔍 Capturing Variables
You can grab outside variables into the lambda using capture lists:
[x]– capture x by value[&x]– capture x by reference[=]– capture everything by value[&]– capture everything by reference
📎 Example: Capture in Action
#include <iostream>
using namespace std;
int main() {
int base = 10;
auto addBase = [base](int x) {
return base + x;
};
cout << "Result: " << addBase(5) << endl;
return 0;
}
✅ Summary
- Lambda expressions = mini functions created on-the-spot.
- Use them when you need a quick action, like inside loops or algorithms.
- They can capture variables from the outer scope.