Click here to Skip to main content
Click here to Skip to main content

Lambda Function in C++

, 21 Jun 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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 [^]
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)

Share

About the Author

ThatsAlok
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!!!
 

For good 8 years he was Visual CPP MSMVP!

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberaydinsahin25-Jun-13 5:36 
AnswerRe: My vote of 5 PinmemberThatsAlok25-Jun-13 23:25 
GeneralMy vote of 4 PinmemberKishore Debnath21-Jun-13 22:44 
GeneralRe: My vote of 4 PinmemberThatsAlok21-Jun-13 22:58 
Questionfeedback PinmemberDan page21-Jun-13 4:12 
AnswerRe: feedback PinmemberThatsAlok21-Jun-13 7:02 
GeneralMy vote of 5 [modified] PinmvpEspen Harlinn20-Oct-12 8:59 
QuestionMy vote of 5 PinmemberJohn Bandela19-Oct-12 6:54 
AnswerRe: My vote of 5 PinmemberThatsAlok19-Oct-12 7:28 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 21 Jun 2013
Article Copyright 2012 by ThatsAlok
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid