欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++ lambda expression

程序员文章站 2022-06-05 18:16:25
Emerged since c++11, lambda expression/function is an unnamed function object capable of capturing variables in scope. 1. syntax of a lambda expressio ......

emerged since c++11, lambda expression/function is an unnamed function object capable of capturing variables in scope.

1. syntax of a lambda expression

[ captures ] <tparams>(optional)(c++20) ( params ) specifiers exception attr -> ret requires(optional)(c++20){ body }

[ captures ] ( params ) -> ret { body }

[ captures ] ( params ) { body }

[ captures ] { body } 

examples:

 [](){}   //barebone lambda

 [](){}() // immediately execute a lambda

auto print = [](const int& n) { n = n+1; std::cout << " " << n; };
std::for_each(v.begin(), v.end(), print); // caller of the lambda expression
std::for_each(v.begin(), v.end(), [](int &n){ n++; });