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

Lambda Expression in C


Visual C++ Visual C++ 
Ratings:
0 Comment(s)
 640  View(s)
Rate this:

Lambda Expression in C++

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>

using namespace std;

using namespace 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#


Don't want to miss updates? Please click the below button!

Follow MindStick