top of page

Lambda Function in C++



Lambda functions are a kind of anonymous functions in C++. These are mainly used as callbacks in C++. Lambda function is like a normal function i.e.

  • You can pass arguments to it

  • It can return the result

But it doesn’t have any name. Its mainly used when we have to create very small functions to pass as a callback to an another API.

Syntax of Lambda Function:

[ capture clause ] (parameters) -> return-type

{

definition of method

}

capture clause:

A lambda with empty capture clause [ ] can access only those variable which are local to it.


We can capture external variables from enclosing scope by three ways : Capture by reference Capture by value Capture by both (mixed capture)

Syntax used for capturing variables : [&] : capture all external variable by reference [=] : capture all external variable by value [a, &b] : capture a by value and b by reference

Parameters: we can pass the parameters in lambda function.

return-type:

return-type in lambda expression are evaluated by compiler itself and we don’t need to specify that explicitly and -> return-type part can be ignored but in some complex case as in conditional statement, compiler can’t make out the return type and we need to specify that.

Example:


#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
int main()
{
 	vector<int> v1 = {2,6,2,9,8,5};
 	for_each (v1.begin(),v1.end(),[](int x) {
 	x=x*2;
 	cout<<x<<endl;
 	});
}

Generic Lambda(C++14):

#include <iostream>
using namespace std;

int main()
{
    auto add = [](auto x,auto y)
    {
        return x+y;
        
    };
    
    cout<<add(10,20)<<endl;
    cout<<add(10.5,20.8)<<endl;
    return 0;
}

Comments


bottom of page