C++11 Tidbits: Lambda Expressions (Part 1)

Completely new in C++1x lambda expressions may sound a bit esoteric but in fact many programming languages already offer support for defining unnamed functions on-the-fly. Of course many are functional programming languages but there are also Java, Python and other languages in common use. The GCC 4.5.x release series and Microsoft Visual Studio delivered lambdas more than one year ago. In GCC many bugs have been fixed since then and the facility can be considered pretty stable by now. The following, taken directly from the FDIS of the new Standard (*), works as a first introductory example:

#include <algorithm>
#include <cmath>

void
abssort (float *x, unsigned N)
{
  std::sort (x, x + N,
   [](float a, float b) { return std::abs(a) < std::abs(b); } );
}

The lambda expression, introduced by the open square bracket, defines an unnamed function object taking the two parameters a and b and returning the value - of boolean type, automatically deduced - of the comparison between the absolute values of a and b themselves. Then, in the example, the std::sort algorithm can use the so-called closure object to which the lambda expression evaluates.

A future tidbit will explain in more practical applications what the open/closed squared brackets are really about. Until then, you are all encouraged to start experimenting right now!

(*) ISO Document N3242. For a large set of examples the older document N2529 is recommended. See some of the references therein for historical background and rationale.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

C++ enthusiasts only, please! ;)

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today