Lambda expression in C++


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. For example,

Example

 Live Demo

#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

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

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

Updated on: 30-Jul-2019

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements