Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / Visual C++ 10.0
Tip/Trick

Lambda Function in C++

Rate me:
Please Sign up or sign in to vote.
4.89/5 (8 votes)
21 Jun 2013CPOL1 min read 37.3K   24   9
Showcase for lambda function in C++

Introduction

Lambda functions are quite popular in .net world and with standardization in C++11, its get included in the language standard and available with VS2010. These are type of function which can be declared anonymously and without having name.

Using the code   

Let go straight to lambda function declaration
[1] (2) ->type {function body}(actual argument);

Here

1 :is parent scope variable to be referred inside the lambda function, multiple variable can be separated by comma, this is quite different from .net world where we don’t need this thing
2 : is the place where you define the parameter list for the anonymous function
type : though this is not compulsory, but you can specify the return type of the lambda function from here
{functionbody} :actual anonymous function code goes here
(actual argument) :actual argument to be passed to this lambda function

Now let discuss it further with the example:-

Ex1 : Lambda function without parameter

This lambda function would return earth gravity as double type

double earthGravity = []()->double { return 9.81;}();

Ex2 : Lambda function with parameter

Say if you want to get area of rectangle by passing length and breath

int rectangleArea = [](int ilength,int iBreath)-> int
                    { return ilength*iBreath;}(10,20);

Here I create a lambda function with two parameter, return type int and passed the argument 10 and 20 and rectangleArea would contain the result 200,  once it's get executed

Ex3 : Lambda function with parent scope variable

Here I am creating two vector, first vector will contain the all the natural number from 1-10 and using lambda function we will add all the even number into the new vector which I going to pass by reference. I have explained the code in comments

#include <iostream>
#include <vector>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	vector <int>vecInt;
	vector <int>evenNumberVec;

	//fill our main vector with dummy data
	for(int iCount =1;iCount<10;iCount++) 
          vecInt.push_back(iCount);

	//get all even number from vector using anonymous function
	bool rFlag =
	[vecInt](vector<int> &vecTmp)->bool{
		vector<int>::const_iterator it = vecInt.begin();
		while(it!=vecInt.end())
		{
			if((*it%2)==0)
				vecTmp.push_back(*it);
			it++;
		}
		return true;
	}(evenNumberVec);

	// print them
	for(int iCount =0;iCount <evenNumberVec.size();iCount++)
                std::cout<<evenNumberVec.at(iCount)<<std::endl;
	return 0;
}

Ex4 : Lambda function with parent scope variable (Pass By Reference)

thanks to Mr John Bandela [^]
C#
bool rFlag =
    [&vecInt,&evenNumberVec]()->bool{
        vector<int>::const_iterator it = vecInt.begin();
        while(it!=vecInt.end())
        {
            if((*it%2)==0)
                evenNumberVec.push_back(*it);
            it++;
        }
        return true;
    }();

Points of Interest  

Lambda’s looks good, hope we will hear more about it in coming days.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
He used to have biography here Smile | :) , but now he will hire someone (for free offcourse Big Grin | :-D ), Who writes his biography on his behalf Smile | :)

He is Great Fan of Mr. Johan Rosengren (his idol),Lim Bio Liong, Nishant S and DavidCrow and Believes that, he will EXCEL in his life by following there steps!!!

He started with Visual C++ then moved to C# then he become language agnostic, you give him task,tell him the language or platform, he we start immediately, if he knows the language otherwise he quickly learn it and start contributing productively

Last but not the least, For good 8 years he was Visual CPP MSMVP!

Comments and Discussions

 
GeneralMy vote of 5 Pin
aydinsahin25-Jun-13 4:36
aydinsahin25-Jun-13 4:36 
AnswerRe: My vote of 5 Pin
ThatsAlok25-Jun-13 22:25
ThatsAlok25-Jun-13 22:25 
GeneralMy vote of 4 Pin
kishoredbn21-Jun-13 21:44
kishoredbn21-Jun-13 21:44 
GeneralRe: My vote of 4 Pin
ThatsAlok21-Jun-13 21:58
ThatsAlok21-Jun-13 21:58 
Questionfeedback Pin
Dan page21-Jun-13 3:12
Dan page21-Jun-13 3:12 
AnswerRe: feedback Pin
ThatsAlok21-Jun-13 6:02
ThatsAlok21-Jun-13 6:02 
GeneralMy vote of 5 Pin
Espen Harlinn20-Oct-12 7:59
professionalEspen Harlinn20-Oct-12 7:59 
QuestionMy vote of 5 Pin
John Bandela19-Oct-12 5:54
John Bandela19-Oct-12 5:54 
AnswerRe: My vote of 5 Pin
ThatsAlok19-Oct-12 6:28
ThatsAlok19-Oct-12 6:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.