C++ lambda expression

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

1. syntax of a lambda expressionexpress

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

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

[ captures ] ( params ) { body }c++11

[ captures ] { body } code

examples:ci

 [](){}   //barebone lambdaget

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

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++; });
相關文章
相關標籤/搜索