Lambda expressions
In C++, the regular function syntax is extended with the concept of a callable, short for callable entity—a callable is something that can be called in the same way as a function. Some examples of callables are functions (of course), function pointers, or objects with the operator()
, also known as functors:
void f(int i); struct G { void operator()(int i); }; f(5); // Function G g; g(5); // Functor
It is often useful to define a callable entity in a local context, right next to the place it is used. For example, to sort a sequence of objects, we may want to define a custom comparison function. We can use an ordinary function for this:
bool compare(int i, int j) { return i < j; } void do_work() { std::vector<int> v; ..... std::sort(v.begin(), v.end(), compare); }
However, in...