What is a lambda expression in C++11?

C++Server Side ProgrammingProgramming

C++ STL includes useful generic functions like std::for_each. Unfortunately, they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function. So this function that you'll create will be in that namespace just being used at that one place. The solution to this is using anonymous functions.

C++ has introduced lambda expressions in C++11 to allow creating anonymous function.

example

#include<iostream>
#include<vector>
#include <algorithm> // for_each

using namespace std;

int main() {
   vector<int> myvector;
   myvector.push_back(1);
   myvector.push_back(2);
   myvector.push_back(3);

   for_each(myvector.begin(), myvector.end(), [](int x) {
      cout << x*x << endl;
   });
}

output

This will give the output −

1
4
9

The (int x) is used to define the arguments that the lambda expression would be called with. The [] are used to pass variables from the local scope to the inner scope of the lambda, this is called capturing variables. These expressions if simple, can auto deduce their types. You can also explicitly provide type information using the following syntax −

Syntax

[](int x) -> double {
   return x/2.0;
}

To explore C++ lambdas in detail head over to this StackOverflow thread − https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11



raja
Published on 28-Feb-2018 13:00:54
Advertisements