By feng
With lambda support, it is easier to write some functional code, such
| 123 |
std::vector<int> vec; std::for_each( vec.begin(), vec.end(), [](int i){ std::cout <<i << ""; } ); |
For example
| 12 |
std::sort( vec.begin(), vec.end(), [](int i, int j) { return std::abs(i) < std::abs(j); } ); |
The
| 1 |
[](int i, int j){return std::abs(i) < std::abs(j);} |
Is a lambda object. The type returned by this anonymous object is
| 1 |
decltype(std::abs(j)<std::abs(j)) |
Note that the return type can be ignored only when a return expression exists in a lambda object; otherwise, it is void. Therefore, this lambda object is written down like this:
| 12 |
[](int i, int j) -> bool{ return std::abs(i) < std::abs(j); } |
[] Is called the lambda-introducer. It can be empty or have several variable names:
[] // No parameters are defined
[X, & y] // x is passed in as a value, and y is passed in as a reference
[&] // All external parameters are passed in as references
[=] // All external parameters are passed in as values
[&, X] // x is passed in as a value, and others are passed in as references
[=, & Z] // z is passed in as a reference, and others are passed in as values
Below is an example of using external parameters
| 1234 |
std::vector<double> arr; double sum = 0; std::for_each( arr.begin(), arr.end(), [&sum](double d){ sum += std::exp(d); } ); |
Sum is passed in as a reference, which is equivalent to Calculation
And save the result to sum.
Of course, the reference of all external parameters can also be directly captured in the preceding section for simplification, which is useful in many parameters.