Home > Backend Development > C++ > body text

C++ function Lambda expression passed as parameter

WBOY
Release: 2024-04-20 09:42:01
Original
1019 people have browsed it

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

Example

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

#include 
#include 

using namespace std;

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

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

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

  return 0;
}
Copy after login

Output

1
2
3
4
5
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!