Preface:
Finally, lambda expressions were introduced in C++11. lambda first came from functional programming. Modern languages have gradually introduced this syntax. C++ is not willing to fall behind and has added lambda expressions to the new standard.
1. Why do you need lambda expressions?
- Easy to use, declare functions or function objects in place, especially for better consumption with bind
- Concise, can be created anonymously, and the syntax looks extremely comfortable
- Functional closures can be implemented, making it more flexible to use
2. Use syntax
Common syntax for lambda: [Capture list] (parameter table) Function options -> Return value type { function body ;};
Capture list
- [] No variables are captured
- [&] Capture all variables in the external scope by reference
- [=] Capture all variables in the external scope as a value
- [= , &x] Captures external scope variables in value, but captures x variables in reference
- [ x ] Capture x variables by value
- [ this ] Capture this pointer of the current class, then the lambda expression has the same permissions as the class member function. If & or = is used, this item is added by default.
mutable affects lambda expression
Even if there are no parameters for the lambda expression modified by mutable, it must write a parameter list. If the mutable is not added, the lambda cannot modify the value of this variable and can only be used. However, the modified lambda expression will define a variable internally and copy this value just like a function passing parameters.
#include <iostream> using namespace std; int main() { size_t t = 9; auto f = [t] () mutable {return ++t; }; cout << f() << endl; //10 cout << f() << endl; //11 cout << "t:" << t << endl; //9 return 0; }
It can be considered a functor with overloaded parentheses operators, and a lambda expression without capturing any variables can be converted into a normal function pointer
//Use std::function to store and manipulate lambda expressionsstd::function<int, int> f1 = [](int a){ return a}; //Convert to a normal function pointerusing fun = int(*){int}; fun f =[](int a){return a;} f(1)
Combined with std::bind and lambda expression
//eg: used to calculate the number of elements greater than 5 and less than 10 in the setauto f = std::(std::logical_and<bool>(), std::bind( std::greater<int>(), _1, 5), std::bind(std::lesss<int>(),_1, 10)); int count = std::count::_if((), (),f);
3. Selection of std::function and lambda expressions
lambda
andstd::function
ofThe effect is the sameBut it's a bit simpler,Can't be completely replaced, because some old libraries do not support lambda expressions
This is the end of this article about the C++11 series of learning Lambda expressions. For more related content of C++11 Lambda expressions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!