Home > Backend Development > C++ > How does a C++ Lambda expression return a result?

How does a C++ Lambda expression return a result?

WBOY
Release: 2024-06-04 10:24:57
Original
499 people have browsed it

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 表达式如何返回结果?

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; // 返回结果
};
Copy after login

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;
}
Copy after login

Explanation:

  • In this Lambda expression, [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.
  • The function body uses conditional statements to check whether num is an odd number. If so, add it to sum and return it, otherwise return sum.
  • Finally, the 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template