Lambda expression in C++

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


 Live Demo

#include <algorithm> // for_each
using namespace std;
int main() {
   vector<int> myvector;
   for_each(myvector.begin(), myvector.end(), [](int x) {
      cout << x*x << endl;



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 22:30:25