Pages

Lambda expressions in C++0x

A lambda expression is a way to implicitely define and construct a functor.

Here is a first example of its usage in C++0x:

#include <iostream>

using std::cout;
using std::endl;

void l01()
{
// no need to explicit the lambda return type in this case:
cout << [](int x, int y) { return x + y; }(4, 5) << endl;

// here the return type has to be explicited
cout << [](int x, int y) -> int { int z = x + y; return z + x; }(3, 5) << endl;
}

In the next example we see how a lambda expression could get access to one or all variable in the local scope, putting, as is said, them in the closure. Notice that if we don't prefix the variable in the closure with an ampersand, we access just a copy of the local variable.

#include <iostream>
#include <vector>
#include <algorithm>

using std::cout;
using std::endl;
using std::vector;
using std::for_each;

void l02()
{
vector<int> vec;
for(int i = 0; i < 10; ++i)
vec.push_back(i);

int total = 0;

// put 'total' as reference in the lambda closure
for_each(vec.begin(), vec.end(), [&total](int x) {total += x;});
cout << total << endl;

// put all the local variables as reference in the lambda closure
for_each(vec.begin(), vec.end(), [&](int x) {total += x;});
cout << total << endl;
}

No comments:

Post a Comment