Significance of Lambda Function in C/C++


Lambda Function − Lambda are functions is an inline function that doesn’t require any implementation outside the scope of the main program.

Lambda Functions can also be used as a value by the variable to store. Lambda can be referred to as an object that can be called by the function (called functors).

Whenever the compiler encounters a definition of the lambda function, it generally creates a custom object for the lambda.

A lambda function has more functionality than a normal function, for example, it has a capturing method to capture the used variables. However, the captured variable is treated as the member of the object.

Sometimes a lambda function is also referred to as a “function object” which has its own scope and can be passed as a parameter inside a normal function. Lambda function has its own lifetime.

[ ] - Capture

( ) - Parameters (Optional)

- Return Value(Optional)

{...} - Function Body.

Syntax of lambda

[ ]( int a) -> int { return a-1 ;};

Capture – A capture is a clause through which the lambda function has given access to variables available in that particular scope or nested block.

We can capture the value of an available variable by using two methods,

  • Capturing the object by Name – Capturing the object by the name makes a local copy of the lambda function.

We can understand this concept with the following example −

int main(){
   set s;
   //Adding the elements to set
   int i=20;
   for_each(s.begin(),s.end(), [i](T& elem){
      cout<<elem.getVal()*i<<endl;
   }
}

In the above example, the value is captured by creating the local copy of the lambda function.

  • Capturing object by reference – Capturing an object by reference manipulates the context of the lambda function. Thus the value captured by the function object or lambda function can be changed.

We can understand this with the following example −

int main(){
   sets;
   //Adding elements to the set
   int result=0;
   for_each(s.begin(),s.end(), [&result](&T elem){ result+= elem.getVal();});
   cout<<result<<endl;
}

Lambda Inside the member function

We know that a lambda function can be used as a parameter inside any normal function. For example,

class func{
public:
   func(set<T>s): s1(s){}
   void func(){
      remove_if(s1.begin(),s1.end(), [this](int i) ->bool {return (i<level);});
   }
private:
   set<T>s1;
   int result;
};

Updated on: 05-Feb-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements