Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Creating Unnamed Functions with the Lambda Library-4 : Page 4

Lambda by Numbers
A unary expression uses one placeholder—the 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.

Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.