My top 5 C++11 language features #2 - lambda expressions

By: Tim DelChiaro

Abstract: Derived from lambda calculus and procedural abstraction, lambda expressions in C++11 (and in other programming languages) are particularly well suited for creating anonymous function

This is a repost of a blog post from Embarcadero's John Thomas. You can get to his blog and the original post by clicking the blog post name below.

  My top 5 C++11 language features #2 - lambda expressions

The countdown continues with my second favorite new C++ 11 language feature - lambda expressions. Lambda expressions have many uses and have been around in other programming languages (mostly dynamic languages) for a while. Derived from lambda calculus and procedural abstraction, lambda expressions in C++11 (and in other programming languages) are particularly well suited for creating anonymous functions.

The basic syntax to create an anonymous functions with a lambda expressions is:

[](parameters)-> return type {body}

The [] operator is called the capture operator, then an optional parameter list is provided within (), followed by an optional return type (C++11 can infer the return type in most cases), and finally the body within curly braces {}; The capture operator basically tells the compiler to "capture" variables within its current scope to make them available in the lambda expression body.

Here is a simple example of binding an lambda expression to a variable, using the complete syntax, that can be called later as a function.

auto f = [] (std:string& s) -> int {std::cout << s; return 0;};

f("hello lambdas");

Now, let’s go a little further with this and get back to anonymous functions. Let’s say I want to run a quick sorting algorithm on an array. The std::sort expects an initial position and final position in the container class (both in the form of std::RandomAccessIterator) and a comparison function with a proper signature. Before, lambda expressions for anonymous functions I would have had to write and declare a separate function with the correct signature. Now, I can just embed it into my sort call as an anyonymous function.

template <typename X>  void sort_vector(std::vector<X>& v)
{
std::sort(v.begin(), v.end(), [] (const X& a, const X& b) {return a < b});
}

So, in addition to closures, lambda expressions enable many other cool features like functors and delegates with much less code and without a pre-processor. How do you envision using lambda expressions?


Server Response from: ETNASC03