Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VC10.0

Lambda Function in C++

4.89/5 (8 votes)
21 Jun 2013CPOL1 min read 38.3K  
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)