C++ 11 lambda function
In C++ 11, a lambda expression is a convenient way of defining an anonymous function object right at the location where it is invoked or passed as an argument to a function.
basic usage:1
2
3
4
5
6[=] (int x) mutable throw() -> int
{
// function
int n = x + y;
return n;
}
[=]:lambda-introducer, or capture clause
every lambda function start with lambda-introducer and can not be omitted. Besides of the working as a keyword for lambda expression, it can also denote how to fetch variables into lambda function.
You can use thedefault capture mode
(capture-default in the Standard syntax) to indicate how to capture any outside variables that are referenced in the lambda:[&]
means all variables that you refer to arecaptured by reference
, and[=]
means they arecaptured by value
. You can use a default capture mode, and then specify the opposite mode explicitly for specific variables.
For example, if a lambda body accesses the external variable total by reference and the external variable factor by value, then the following capture clauses are equivalent:[]
: default[=]
: set default capture mode to capture by value.[&]
: set default capture mode to capture by reference.[x, &y]
: x is capture by value, y is capture by reference.[=, &y]
: every variable is captured by value, except y is captured by reference.[&, x]
: every variable is captured by reference, except x is captured by value.
use lambda with STL function:
example(with out lambda):1
2
3
4
5
6
7
8
9
10
11
12
13
14
15bool condition(int value) {
return (value > 5);
}
int main() {
vector<int> numbers { 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
// check how many elements meet the condition
auto count = count_if(numbers.begin(), numbers.end(), condition);
cout << "Count: " << count << endl;
}
vector<int> numbers { 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
// use lambda expression to replace the condition function
auto count = count_if(numbers.begin(), numbers.end(), [](int x) { return (x > 5); });
cout << "Count: " << count << endl;
reference:
https://msdn.microsoft.com/en-us/library/dd293608.aspx
https://blog.gtwang.org/programming/lambda-expression-in-c11/