2011-09-07 CPlusPlus0X

Lambda expressions

For defining small functions at the very spot they are used C++ introduces lambda expressions. A lambda expression is like a short function that can be used where a normal function would be called. Here is an example of a predicate functions that returns true for odd numbers:

[](int x) { return x % 2 == 1; }

This specifies a lambda expression taking one int parameter. The return type is defined by the type of the return statement. Yet a place where compact notation has been chosen. It can be put to use in a count_if algorithm like this:

list<int> numbers {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int numberOfOdd = count_if(numbers.begin(), numbers.end(), [](int x) { return x % 2 == 1; });

No need to define a local predicate functions. The lambda expression can be used right in place.

But there is more. We just saw that a lambda can take arguments but it can also bind to variables in the scope of its creation like this:

int sum = 0;
for_each(numbers.begin(), numbers.end(), [&sum](int x) { sum += x; });

The variable sum is available in the lambda and it is accessed by reference. The [&sum] notation in the beginning of the lambda expression defines this binding.

In the next posting we'll look more into the closure aspects of lambdas.