C++ Lambda Expressions Tutorial
Lambda expressions in C++ provide a way to create anonymous functions, making your code more concise and functional-style.
Basic Syntax
// Lambda Syntax: [capture](parameters) { body }
auto add = [](int a, int b) {
return a + b;
};
std::cout << add(2, 3); // Outputs: 5
Capturing Variables
You can capture variables from the surrounding scope:
int x = 10, y = 20;
auto sum = [x, y]() {
return x + y;
};
std::cout << sum(); // Outputs: 30
Mutable Lambdas
To modify captured variables, use the mutable keyword:
int num = 5;
auto increment = [num]() mutable {
return ++num;
};
std::cout << increment(); // Outputs: 6
Generic Lambdas
With C++14, lambdas can be made generic using auto:
auto multiply = [](auto a, auto b) {
return a * b;
};
std::cout << multiply(3, 4.5); // Outputs: 13.5
Applications
- Sorting: Use lambdas for custom sorting.
- Callbacks: Provide inline functions as arguments.
- Concurrency: Combine lambdas with threading.
×