Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
The use of lambda expressions is a technique that can be used, depending on the standard used:
The speed of C++98 Boost.Lambda and C++11 lambda expressions are compared and profiled (for only one simple function) in Answer of exercise #7: AddOne.
lambda expressions are not directly supported by the C++98 standard. Boost.Lambda, however, can be used instead:
#include <algorithm> |
Prefer a named function object to a lambda expression if the operation requires comments [3]. Prefer a named function object to a lambda expression if the operation is generally useful [4]. Keep lambda expressions short [5]. For maintainability and correctness, be careful about capture by reference in a lambda expression [6]. Let the compiler deduce the return type of a lambda expression [7].
lambda expressions can be used for on-the-fly functors:
#include <algorithm> |
Let's zoom in at the lambda expressions:
std::sort(v.begin(),v.end(), |
The '[]' denotes that there is an empty capture list: the lambda expressions does not need to be fed a constant from its environment. The '(const int a, const int b)' are the names and data types to lambda expressions works on: for sorting one needs two arguments: these are called 'a' and 'b' and are const integers. Finally, the '{ return std::abs(a) < std::abs(b); }' describes how the arguments are used to draw a conclusion.
The example below does not show a capture list, the example below does:
//C++11 lambda expression |
In the example above, 'x' is in the capture list: the capture list consists of variables that are needed in the lambda expressions.
Program flow in a C++11 lambda expression differs from a C++98 lambda expression or BOOST_FOREACH: if you want to return from a function, all that happens is that the std::for_each (or other algorithm) is terminated. The example below shows this.
#include <algorithm> |
Screen output:
FOUND! |
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.