Home >Backend Development >C++ >The meaning of Lambda function in C/C++

The meaning of Lambda function in C/C++

WBOY
WBOYforward
2023-09-02 19:33:081478browse

The meaning of Lambda function in C/C++

Lambda Function - A Lambda function is an inline function that does not require any implementation outside the scope of the main program.

Lambda functions can also be used as the value of a variable to be stored. Lambdas can be called objects (called functors) that can be called by functions.

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

The lambda function has more features than a normal function, for example, it has a capture method to capture the variables used. However, captured variables are treated as members of the object.

Sometimes lambda functions are also called "function objects", which have their own scope and can be passed as parameters within ordinary functions. Function. Lambda functions have their own life cycle.

[ ] - Capture

( ) - Parameters (optional)

- Return value (optional)

{...} - Function body.

lambda Syntax

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

Capture – Capture is a clause through which a lambda function can access variables available in a specific scope or nested block.

We can capture a certain value by using two methods to get the available variables:

  • Capturing an object by name – Capturing an object by name will A lambda function that generates a local copy of the object.

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 a local copy of the lambda function.

  • Capturing objects by reference – Capturing objects by reference allows you to manipulate the context of a lambda function. Therefore, the value captured by a function object or lambda function can change.

We can understand this through 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 member function

We know that lambda function can be inside any ordinary function used as parameters. 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;
};

The above is the detailed content of The meaning of Lambda function in C/C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete