Lambda by Numbers
A unary expression uses one placeholderthe predefined variable
_1. The lambda library defines two more placeholders:
_2 and
_3 for binary and ternary functors, respectively. These placeholders are useful for creating an unnamed function taking two and three operands, respectively. Let's look at an example.
Suppose you have a container of pointers that needs to be sorted. The default sort() implementation will sort the bare pointers, which isn't what you usually want. To override this behavior, provide a lambda functor as the third argument:
struct Foo
{
//..
};
vector <Foo *> vp;
//..populate the container
sort(vp.begin(), vp.end(), *_1 < *_2);//ascending
Let's see how it works.
vp[n] is a pointer. Hence, the placeholders
_1 and
_2 represent pointers. The complete lambda expression dereferences these pointers and returns a Boolean value indicating whether
*_1 is less than
*_2. This binary lambda functor ensures that the sorting operation produces the desired results.
Lambda Unlimited
The lambda library has many other constructs for defining if-then-else statements, exception handling, switch statements and the sizeof and typeid operators. Although you've only seen the basic features of the lambda library here, it's clear that it's a very powerful addition to the C++ Standard Library.