Lambdas in C++
Writing lambda functions in C++, capture by value and by reference, and using lambdas with STL algorithms.
A lambda is an unnamed function you can write inline: [capture](parameters) { body }.
The capture list decides which outside variables it can use:
[x]copiesxwhen the lambda is created.[&x]refers to the realx(it must outlive the lambda).[=]and[&]capture everything used, by copy or by reference.
Lambdas are most useful as arguments to algorithms like std::sort, std::count_if and std::transform.
Example
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{5, 12, 7, 20, 3};
int limit = 6;
auto big = std::count_if(v.begin(), v.end(), [limit](int x) { return x > limit; });
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
std::cout << big << " " << v.front() << "\n";
return 0;
}
Output:
3 20