Home >Backend Development >C++ >How to define and use C++ lambda expressions?
C Lambda expression is an anonymous function, used to define functions inline, using the syntax: [capture list](parameters) -> return_type {function body}. They can capture variables in the outer scope, pass parameters, and specify return types. Lambda expressions are used when you need to pass a function as a parameter or define a function in some context, such as passing parameters, capturing variables, and sorting lists.
C Lambda Expressions: Definition and Usage
Introduction
Lambda Expressions are C A special kind of anonymous function in the language that allows you to define inline functions in a concise way. They are widely used in situations where you need to pass a function as a parameter or define a function in some context.
Syntax
The Lambda expression syntax is as follows:
[capture list](parameters) -> return_type { // 函数体 }
Capture list
The capture list is used to capture the outer scope of the lambda expression variables within. Variables can be captured by value or by reference.
Parameters
The parameter list allows you to pass parameters to the lambda expression.
Return type
If the lambda expression returns a value, you need to specify the return type. Otherwise, the return type should be void
.
Function body
Similar to a normal function, the function body contains the code to be used as a lambda expression.
Usage
The following are some examples of using lambda expressions:
Basic example
[]() { std::cout << "Hello, world!" << std::endl; }();
Passing parameters
int add(int a, int b) { return a + b; } [] (int a, int b) { return a + b; }(5, 6); // 调用 lambda 表达式
Capturing variables
int x = 10; [x] () { std::cout << "Value of x: " << x << std::endl; }();
Practical case
Consider an example where numbers in a list need to be sorted :
std::vector<int> numbers = {2, 5, 1, 3, 4}; std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a < b; }); for (auto num : numbers) { std::cout << num << " "; }
Output:
1 2 3 4 5
Conclusion
Lambda expressions are a powerful tool for defining inline functions in C. They simplify code, improve readability and reduce the need for boilerplate code. By understanding their syntax, usage, and practical examples, you can effectively use lambda expressions to solve a variety of programming problems.
The above is the detailed content of How to define and use C++ lambda expressions?. For more information, please follow other related articles on the PHP Chinese website!