lambda expression in C++11 and C++14?

Lamda expression in C++11 and C++14 is way of making anonymous function object. The below figure explains the basic syntax of Lamda expression. The starting syntax [] is known as Lamda introducer.

Lambda expression in C++11 and C++14A very simple example of Lambda expression

How to compile:
bosch@bosch-Inspiron-N5050:~$ g++ -std=c++11 lamda.cpp

A practical example of Lamda expression’s advantage

Let us write a old c++ code for displaying elements of a vector using for_each. To display the elements of a vector using for_each in old C++ wee need to write a trivial routine first.

We can use Lamda expression [](int n){cout<<n<<endl;} inside for_each inline to display the vector elements. The above code in c++ 11 can be written as

In all above example we have used empty capture list in lamda introducer []. we can capture list as value or reference. we can capture by value or reference inside [].

capture by value example:

capture by reference by value :

capture by reference by reference :

  • []  empty capture list.
  • [=] capture any reference within lamda by value ( copy of divisor would happen).
  • [&] capture any reference variable within lamda by reference.

C++14 Generalized Lamda enhancement over C++11 Lamda

Follow the next link


Related Contents to follow