A lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it is invoked or passed as an argument to a function.
Smallest Lambda Expression :
[]() {};
I have explained Lambda Functions in a number of steps to get a clear understanding.
- Hello Word Example Lambda Functions :
int main()
{
auto SayHello = []() { cout << “Hello Word Example for lambda expressions in c++” << endl; };
SayHello();
return 0;
}
2. Passing Parameters in Lambda Functions :
int main()
{
auto SayHello = [](int b, int a) -> void // -> optional
{
cout << “Hello Word Example for lambda expressions in c++ : ” << a+b << endl;
};
SayHello(10, 20);
return 0;
}
3. Using Parameters from outside scope- By Value :
int main()
{
int i = 20;
int j = 30;
auto SayHello = [i, j](int b, int a)
{ // i and j are constant since it is passed as value
//i++/ j++ Error- i is constant
cout << “Hello Word
Example for lambda expressions in c++ : ” << a+b+i << endl;
};
SayHello( 10,20);
return 0;
}
4. Using Parameters from outside scope- By Reference :
int main()
{
int i = 20;
auto SayHello = [&i](int b, int a)
{
i = 100; //value of i updated to 100
cout << “Hello Word Example for lambda expressions in c++ : ” << a+b+i<< endl;
};
SayHello( 10, 20);
return 0;
}
5. Passing All Parameters from outside scope- By Value :
auto SayHello = [=](int b, int a)
{
….. // i and j are constant
}
6. Passing All Parameters from outside scope- By Reference :
auto SayHello = [&](int b, int a)
{
….. // allowed to modify i & j
}
7. All parameters constant except i :
auto SayHello = [= , &i](int b, int a)
{
….. // cannot modify j
}
8. All parameters non-constant except i :
auto SayHello = [& , i](int b, int a)
{
….. // cannot modify i
}
9. Lambda in for_each :
int main()
{
vector vecValue = { 10, 20, 30, 40, 50 };
int total = 0;
for_each (begin(vecValue),end(vecValue), [&](int x) { total = total + x; });
cout << total<< endl;
return 0;
}
10. Lambda Expression in functional :
void lambdainStdFunction(function f)
{
f();
}
int main()
{
int nTotal = 0;
auto func = [&]() { nTotal = 100; };
//Output : Value of Total before = 0
lambdainStdFunction(func);
//Output : Value of Total before = 100
cout << nTotal << endl;
return 0;
}
External links for reference:
Cppreference Link for reference: https://en.cppreference.com/w/cpp/language/lambda
Wiki Reference for Tuple: https://en.wikipedia.org/wiki/Anonymous_function#C++_(since_C++11)