This is the 15th day of my participation in the More text Challenge. For more details, see more text Challenge


Lambda expressions
C++11Support is provided for anonymous functions, called Lambda functions (also called Lambda expressions). Lambda expressions treat functions as objects. Lambda expressions can be used like objects. For example, they can be assigned to variables and passed as arguments, and they can be evaluated like functions. Lambda expressions are essentially very similar to function declarations. [capture](parameters)->return-type{body} For example, [](int x, int y){ returnx < y ; } If no value is returned, run the following command: [capture](parameters){body} For example: []{++global_x; } In a more complex example, the return type can be explicitly specified as follows: [](int x, int y) -> int { int z = x + y; returnz + x; } In this example, a temporary parameter z is created to store intermediate results. As with functions in general, the value of z is not retained until the next time the unnamed function is called. If the lambda function does not return a value (for examplevoid), whose return type can be completely ignored. Variables of the current scope can be accessed within a Lambda expression. This is the Closure behavior of Lambda expressions. Unlike JavaScript closures, C++ variable passing can be distinguished between passing values and passing references. This can be specified by using the preceding [] : []// No variables are defined. Using an undefined variable raises an error.
[x, &y] // X is passed as a value (default) and y is passed as a reference.
[&]     // Any external variable that is used is implicitly referenced by reference.
[=]     // Any external variable that is used is implicitly referred to as a pass-value.
[&, x]  // x is explicitly referenced as a pass-value. The rest of the variables are referenced by reference.
[=, &z] // z is explicitly referenced by reference. The rest of the variables are referenced by passing values.One more thing to note. For the forms [=] or [&], lambda expressions can be used directlythisPointer. However, for the [] form, if you want to usethisPointer, which must be explicitly passed: [this] () {this->someFunc(a); } ();Copy the code

The instance

#include <algorithm>
#include <cmath>
void abssort(float* x, unsigned N) {
    std::sort(x, x + N,
        // Lambda expression begins[] (float a, float b) {
            return std::abs(a) < std::abs(b);
        });
}
Copy the code