Home > Article > Backend Development > How does a C++ Lambda expression return a result?
C++ Lambda expressions can use the return statement to return results: Syntax: [capture-list] (parameters) -> return-type { // Function body // return expression; } Practical combat: Lambda expressions can be used to filter odd numbers and calculate its sum: int sum_odd = std::accumulate(numbers.begin(), numbers.end(), 0, [](int sum, int num) { if (num % 2 == 1) { return sum + num; } return sum; });
C++ Lambda expression: mechanism for returning results
Lambda expression is an anonymous function in C++ , can be used to represent short and simple blocks of code. We can return results in a Lambda expression by using the return
statement in its syntax.
Syntax:
[capture-list] (parameters) -> return-type { // 函数体 return expression; // 返回结果 };
Practical case:
Assume we have a container numbers
, we Need to return the sum of all odd numbers in the container. We can use Lambda expression as follows:
#include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // 使用 Lambda 表达式过滤奇数 int sum_odd = std::accumulate(numbers.begin(), numbers.end(), 0, [](int sum, int num) { if (num % 2 == 1) { return sum + num; } return sum; }); std::cout << "奇数总和:" << sum_odd << std::endl; return 0; }
Explanation:
[sum, num]
is the capture list, which contains the external variables we need. (sum, num)
is a parameter list, which receives two parameters: sum
is the accumulated value, num
is the current value in the container value. -> int
specifies the return type, in this case int
. num
is an odd number. If so, add it to sum
and return it, otherwise return sum
. std::accumulate
function uses a Lambda expression as a binary operator to accumulate all odd numbers in the container into sum_odd
. With the above method, we can easily return results from functions using Lambda expressions.
The above is the detailed content of How does a C++ Lambda expression return a result?. For more information, please follow other related articles on the PHP Chinese website!