Anonymous function, also known as lambda expression, is a function without specifying a name, used for one-time use or passing function pointer. Features include: anonymity, one-time use, closures, return type inference. In practice, it is often used for sorting or other one-time function calls.
C Usage and characteristics of anonymous functions
Anonymous functions, also called Lambda expressions, are Functions without specifying a name are usually used to define one-time-use functions or when a function pointer needs to be passed.
Syntax
The basic syntax of Lambda expression is as follows:
[capture list] (parameters) -> return type { function body }
auto
keyword in a function, can specify the variable name or reference to be captured. Features
Practical case
The following is an example of sorting vectors using Lambda expressions:
#include <vector> #include <algorithm> int main() { std::vector<int> vec = { 1, 3, 2, 5, 4 }; // 使用Lambda表达式对向量排序 std::sort(vec.begin(), vec.end(), [](int a, int b) { return a < b; }); // 输出排序后的向量 for (auto& elem : vec) { std::cout << elem << " "; } std::cout << std::endl; return 0; }
Output:
1 2 3 4 5
The above is the detailed content of Usage and characteristics of C++ anonymous functions. For more information, please follow other related articles on the PHP Chinese website!