Home  >  Article  >  Backend Development  >  C++ function Lambda expression passed as parameter

C++ function Lambda expression passed as parameter

WBOY
WBOYOriginal
2024-04-20 09:42:011139browse

C's Lambda expression can be passed as a parameter to other functions, the syntax is: auto lambda_function = [](parameter_list) -> return_type { ... }. For example, the for_each function receives as arguments a vector and a lambda expression that performs a specified operation (such as printing the vector elements to the console).

C++ 函数 Lambda 表达式作为参数传递

C function Lambda expression is passed as a parameter

Lambda expression is a small anonymous function that can be passed as a parameter to other functions. This is useful when one or two lines of code need to be passed as parameters.

Syntax

auto lambda_function = [](parameter_list) -> return_type {
  // lambda 函数体
};

Example

The following is an example of a C function receiving a lambda expression as a parameter:

#include <iostream>
#include <vector>

using namespace std;

void for_each(const vector<int>& v, function<void(int)> f) {
  for (int i : v) {
    f(i);
  }
}

int main() {
  vector<int> v = {1, 2, 3, 4, 5};

  // lambda 表达式作为 for_each 函数的参数
  for_each(v, [](int i) {cout << i << endl; });

  return 0;
}

Output

1
2
3
4
5

In this example, the for_each function accepts a vector and a lambda expression as parameters. A lambda expression is used as a callback function that performs a specified operation on each vector element (in this case, the output element).

The above is the detailed content of C++ function Lambda expression passed as parameter. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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