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.


#include <algorithm> // for_each

using namespace std;

int main() {
   vector<int> myvector;

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


This will give the output −


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;

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

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