C++
Lambda Expressions
Lambda and captures.
By EZ4Code Team
lambdafunctional
Code
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
int main() {
int x = 10, y = 20;
// Capture by value
auto add1 = [x, y]() { return x + y; };
// Capture by reference
auto add2 = [&x, &y]() { return x + y; };
// Capture all by value
auto add3 = [=]() { return x + y; };
// Capture all by reference
auto add4 = [&]() { x++; y++; };
// Mixed capture
auto mixed = [x, &y]() { y += x; };
// mutable Lambda
int count = 0;
auto counter = [count]() mutable { return ++count; };
// Generic Lambda (C++14)
auto print = [](const auto& v) {
std::cout << v << std::endl;
};
print(42);
print("hello");
// Used in STL algorithms
std::vector<int> nums = {3, 1, 4, 1, 5, 9};
std::sort(nums.begin(), nums.end(), [](int a, int b) {
return a > b; // Descending order
});
// std::function storage
std::function<int(int, int)> op = [](int a, int b) { return a * b; };
std::cout << op(3, 4) << std::endl;
return 0;
}Explanation
Lambda captures variables via the [] capture list; = captures by value, & by reference; mutable allows modifying captured values.