blog

Home / DeveloperSection / Blogs / Lambda Expression in C++

Lambda Expression in C++

priyanka kushwaha2755 06-Feb-2015

In this blog, I’m explaining about Lambda expression in C++

1 .Lambda Expression provides a concise function syntax for writing anonymous method.

2. It is type safe way to write functions that can be passed as argument for subsequent evaluated.

3. Lambda expression are superset of anonymous method.

4. It can contain either and statement or an expression.

5. It may have or may not have parameter.

6. Its parameter could be implicitly or explicitly  type.

The syntax is:
[ capture-list ]( parameter-list )-> return_type { statements }

Example

#include"stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
usingnamespace std;
usingnamespace System;
 
int main(array<System::String ^> ^args)
{
           
 
            int x=42;
            int y=99;
            int z=100;
            auto lambda=[=,&z]()->int
            {
                        z++;
                       
                        cout<<x<<endl;cout<<y<<endl;cout<<z<<endl;
                        return z;
            };
 z=lambda();
            cout<<z<<endl;
            Console::ReadKey(0);
    return 0;
}
 Example 2:
int x=10;
            int y=20;
            auto lambda=[x,&y]()mutable
            {
                        x++;y++;
                        cout<<x<<endl;cout<<y;
            };
            lambda();
            cout<<x<<endl;cout<<y;

 

Example:
auto lambda=[]()
            {cout<<"Code within  a lambda expression"<<endl;
            };
            auto lambdaexp=[]{cout<<"code with a lambda expression"<<endl;};
     lambdaexp();
            auto sum=[](int x,int y)
            {
                        return x+y;
            };
            cout<<sum(2,3);
            int x = 4;
            int r;
auto y = [& r, x]()->int {
    r += 2;
    return x+2;
}();

     If you like to read the Lambda Expression in C#


Updated 06-Feb-2015

Leave Comment

Comments

Liked By