Lambdas
Contents
Invocation
File: lambdas14.cpp
#include <algorithm> #include <array> #include <string> #include <functional> #include <iostream> using namespace std ; int main() { int num1 = 1; int num2 = 2; auto lambda1Obj = [] (int a, int b) { return a + b; } ; cout << "lambda1Obj invoked: " << lambda1Obj( 5,6) << endl ; //invoked right away auto sum = [] (int a, int b) { return a + b; } (num1, num2); cout << "The sum of " << num1 << " and " << num2 << " is " << sum << endl ; }
Output:
$ g++ lambdas14.cpp ; ./a.exe
lambda1Obj invoked11
The sum of 1 and 2 is 3
We have seen how the lambda expression can be evaluated.
We can invoke it inline or we can assign it to a lambda
object and then call the lambda as shown in the code above.
auto lambda1Obj = [] (int a, int b) {
return a + b;
} ;
cout << "lambda1Obj invoked: " << lambda1Obj( 5,6) << endl ;
The above snippet shows the lambda object being created. We can
also have the expression executed at the point of definition with
the below snippet.
//invoked right away
auto sum = [] (int a, int b) {
return a + b;
} (num1, num2);
cout << "The sum of " << num1 << " and " << num2
<< " is " << sum << endl ;
Here the variable "sum" is of type integer. The lambda
expression gets executed with arguments "num1" and "num2" .