LAMBDA EXPRESSIONS

A lambda expression provides you with an alternative programming mechanism to function objects. Lambda expressions are a C++ language feature and not specific to STL but they can be applied extensively in this context, which is why I chose to discuss them here. A lambda expression defines a function object without a name, and without the need for an explicit class definition. You would typically use a lambda expression as the means of passing a function as an argument to another function. A lambda expression is much easier to use and understand, and requires less code than defining and creating a function object. Of course, it is not a replacement for function objects in general.

Let’s consider an example. Suppose you want to calculate the cubes (x3) of the elements in a vector containing numerical values. You could use the transform() operation for this, except that there is no function object to calculate cubes. You can easily create a lambda expression to do it, though:

double values[] = { 2.5, -3.5, 4.5, -5.5, 6.5, -7.5};
vector<double> cubes(_countof(values));
transform(begin(values), end(values), begin(cubes),
                                            [](double x){ return x*x*x;} );

The last statement uses transform() to calculate the cubes of the elements in the array, values, and store the result in the vector cubes. The lambda expression is the last argument to the transform() function:

[](double x){ return x*x*x;}

The opening square brackets are called the lambda introducer, because they mark ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.