Passing parameters through the capture list, lambda expressions can access external variables. Taking int type parameters as an example, the capture list is [x](int y), where x is an external variable and y is a lambda expression parameter. Using this technique, lambda expressions can be used in various scenarios, such as array summation, where the std::accumulate function accumulates array elements into a variable with an initial value of 0, which is accumulated one by one through the lambda expression.
Lambda expression is a simplified anonymous function that is widely used in C++ to concisely and efficiently Define inline functions. In order for a lambda expression to access external variables, a capture list is used. The same goes for passing parameters.
The capture list precedes the lambda expression parameter list and is enclosed by [
and ]
. It can capture local variables and external variables. To pass parameters, you need to specify the parameter type and name in the capture list.
// 捕获列表传递 int 参数 auto lambda = [x](int y) { return x + y; };
The above example defines a lambda expression lambda
, which receives a int
type parameter named y
and can be accessed External local variable x
.
Consider a scenario where all elements in an array need to be summed. This can be simplified using a lambda expression with a capture list passed as argument:
#include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; int sum = std::accumulate(numbers.begin(), numbers.end(), 0, [](int x, int y) { return x + y; }); std::cout << "Sum: " << sum << std::endl; return 0; }
In this example, the std::accumulate
function uses the provided lambda expression to ## The elements in #numbers are accumulated one by one into
sum with an initial value of
0. A lambda expression takes two integer arguments
x and
y and returns their sum.
to represent by value and
& to represent by reference.
The above is the detailed content of How to pass parameters in C++ Lambda expression?. For more information, please follow other related articles on the PHP Chinese website!