C++ lambda expression
I am trying to understand lambda expression.
开发者_如何学CIts going over my head. Need self explanatory examples
Please !
If you are familiar with the current C++ functors (i.e., classes that implement operator()
so that they can be called like a function, but have internal data-members that can be initialized), then basically lambdas are a nice extension to that language feature by enabling you to create functors as well as initialize them at the point where they are going to be called rather than having to define functor classes. Lambdas are also quite flexible as they can be closures, allowing you to "capture" the values of any variables in the current scope.
I felt this was a really great resource on the Visual C++ Team Blog that went through a lot of these features: Lambdas, auto, and static_assert: C++0x Features in VC10, Part 1
Hope this helps,
Jason
A lambda expression is a mechanism for specifying a function object. The primary use for a lambda is to specify a simple action to be performed by some function. For example:
vector<int> v = {50, -10, 20, -30};
std::sort(v.begin(), v.end()); // the default sort
// now v should be { -30, -10, 20, 50 }
// sort by absolute value:
std::sort(v.begin(), v.end(), [](int a, int b) { return abs(a)<abs(b); });
// now v should be { -10, 20, -30, 50 }
The argument [&](int a, int b) { return abs(a)<abs(b); }
is a "lambda" (or "lambda function" or "lambda expression"), which specifies an operation that given two integer arguments a and b returns the result of comparing their absolute values.
The [&] is a "capture list" specifying that local names used will be passed by reference. We could have said that we wanted to "capture" only v, we could have said so: [&v]. Had we wanted to pass v by value, we could have said so: [=v]. Capture nothing is [], capture all by references is [&], and capture all by value is [=].
http://www2.research.att.com/~bs/C++0xFAQ.html#lambda
A lambda expression (also known as a lambda function) is nameless function defined at the place of call.
For examples, visit Examples on Lambda Expression
Better places to learn :
- Lambda Expression in C++
- Lambda Expression Syntax
Also another example if you'd like :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
// Initialization C++0x-style
vector<int> voo = { 1, 2, 3, 4, 5 };
// Lambda is here
auto print = [&](int& i) { cout << i << endl; } ;
// Check that out, no loop !
for_each(voo.begin(), voo.end(), print);
return 0;
}
Lambda is simple. Remember generic syntax 1st
[ capture list ] (parameters) -> return-type
{
method definition
}
Usually, return-type of a Lambda function is evaluated by the compiler itself and we don’t need to specify that explicitly i.e. -> return-type.
Rest is C++.
For example
Capturing objects
- [ ] ( ) { } no captures
- [=] ( ) { } captures everything by copy(not recommendded)
- [&] ( ) { } captures everything by reference(not recommendded)
- [x] ( ) { } captures x by copy
- [&x] ( ) { } captures x by reference
- [&, x] ( ) { } captures x by copy, everything else by reference [=, &x] ( ) { } captures x by reference, everything else by copy
Capturing this pointer
class Example
{
public:
Example() : m_var(10) {}
void func()
{
[=]() { std::cout << m_var << std::endl; }();
}
private:
int m_var;
};
int main()
{
Example e;
e.func();
}
this
pointer can also be captured using [this], [=] or [&]. In any of these cases, class data members(including private) can be accessed as you do in normal method.
- Lambda as parameter
template <typename Functor>
void f(Functor functor)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
/* Or alternatively you can use this
void f(std::function<int(int)> functor)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
*/
int g() { static int i = 0; return i++; }
int main()
{
auto lambda_func = [i = 0]() mutable { return i++; };
f(lambda_func); // Pass lambda
f(g); // Pass function
}
Output:
Function Type : void f(Functor) [with Functor = main()::<lambda(int)>]
Function Type : void f(Functor) [with Functor = int (*)(int)]
Source: Learn Lambda function in C++ with example
精彩评论