Lambda Expressions in C++

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

11/7/2014

Lambda Expressions in C++

LambdaExpressionsinC++
VisualStudio2013

17outof23ratedthishelpful

InVisualC++,alambdaexpressionreferredtoasalambdaislikeananonymousfunctionthatmaintainsstateandcanaccessthevariablesthatareavailabletotheenclosingscope.
Itdoesthisbydefiningaclassandconstructinganobjectofthattype.Thisarticledefineswhatlambdasare,comparesthemtootherprogrammingtechniques,describestheir
advantages,andprovidesabasicexample.

AboutLambdas
Manyprogramminglanguagessupporttheconceptofananonymousfunction,whichisafunctionthathasabody,butdoesn'thaveaname.Alambdaisaprogrammingtechnique
that'srelatedtoanonymousfunctions.Alambdaimplicitlydefinesafunctionobjectclassandconstructsafunctionobjectofthatclasstype.Formoreinformationaboutfunction
objects,seeFunctionObjects.
Asanintroductoryexampleofalambda,theISOC++Standardshowsoneusedinthecontextofaparameterpassedtothestd::sort()function:
C++
#include<algorithm>
#include<cmath>
voidabssort(float*x,unsignedn){
std::sort(x,x+n,
//Lambdaexpressionbegins
[](floata,floatb){
return(std::abs(a)<std::abs(b))
}//endoflambdaexpression
)
}
Thisarticleexplainshowthisexpressionworks.
Important
Lambdasarenotsupportedinthefollowingcommonlanguageruntime(CLR)managedentities:refclass,refstruct,valueclass,orvaluestruct.

FunctionObjectsvs.Lambdas
Whenyouwritecode,youprobablyusefunctionpointersandfunctionobjectstosolveproblemsandperformcalculations,especiallywhenyouuseSTLalgorithms.Functionpointers
andfunctionobjectshaveadvantagesanddisadvantagesforexample,functionpointershaveminimalsyntacticoverheadbutdonotretainstatewithinascope,andfunctionobjects
canmaintainstatebutrequirethesyntacticoverheadofaclassdefinition.
Alambdacombinesthebenefitsoffunctionpointersandfunctionobjectsandavoidstheirdisadvantages.Likeafunctionobjects,alambdaisflexibleandcanmaintainstate,butunlike
afunctionobject,itscompactsyntaxdoesn'trequireaclassdefinition.Byusinglambdas,youcanwritecodethat'slesscumbersomeandlesspronetoerrorsthanthecodeforan
equivalentfunctionobject.
Thefollowingexamplescomparetheuseofalambdatotheuseofafunctionobject.Thefirstexampleusesalambdatoprinttotheconsolewhethereachelementinavectorobjectis
evenorodd.Thesecondexampleusesafunctionobjecttoaccomplishthesametask.

Example1:UsingaLambda
Thisexampleusesalambdathat'sembeddedinthefor_eachfunctioncalltoprinttotheconsolewhethereachelementinavectorobjectisevenorodd.

Code
C++
//even_lambda.cpp
//compilewith:cl/EHsc/nologo/W4/MTd
#include<algorithm>
#include<iostream>
#include<vector>
usingnamespacestd
intmain()
{
//Createavectorobjectthatcontains10elements.
vector<int>v
for(inti=1i<10++i){
v.push_back(i)
}
//Countthenumberofevennumbersinthevectorby
//usingthefor_eachfunctionandalambda.

http://msdn.microsoft.com/en-us/library/dd293608.aspx

1/3

11/7/2014

Lambda Expressions in C++


intevenCount=0
for_each(v.begin(),v.end(),[&evenCount](intn){
cout<<n
if(n%2==0){
cout<<"iseven"<<endl
++evenCount
}else{
cout<<"isodd"<<endl
}
})
//Printthecountofevennumberstotheconsole.
cout<<"Thereare"<<evenCount
<<"evennumbersinthevector."<<endl
}

Output
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
There are 4 even numbers in the vector.

Comments
Intheexample,thethirdargumenttothefor_eachfunctionisalambda.The[&evenCount]partspecifiesthecaptureclauseoftheexpression,(intn)specifiestheparameter
list,andremainingpartspecifiesthebodyoftheexpression.

Example2:UsingaFunctionObject
Sometimesalambdawouldbetoounwieldytoextendmuchfurtherthanthepreviousexample.Thenextexampleusesafunctionobjectinsteadofalambda,togetherwiththe
for_eachfunction,toproducethesameresultsasExample1.Bothexamplesstorethecountofevennumbersinavectorobject.Tomaintainthestateoftheoperation,the
FunctorClassclassstoresthem_evenCountvariablebyreferenceasamembervariable.Toperformtheoperation,FunctorClassimplementsthefunctioncalloperator,
operator().TheVisualC++compilergeneratescodethatiscomparableinsizeandperformancetothelambdacodeinExample1.Forabasicproblemliketheoneinthisarticle,the
simplerlambdadesignisprobablybetterthanthefunctionobjectdesign.However,ifyouthinkthatthefunctionalitymightrequiresignificantexpansioninthefuture,thenuseafunction
objectdesignsothatcodemaintenancewillbeeasier.
Formoreinformationabouttheoperator(),seeFunctionCall(C++).Formoreinformationaboutthefor_eachfunction,seefor_each.

Code
C++
//even_functor.cpp
//compilewith:/EHsc
#include<algorithm>
#include<iostream>
#include<vector>
usingnamespacestd
classFunctorClass
{
public:
//Therequiredconstructorforthisexample.
explicitFunctorClass(int&evenCount)
:m_evenCount(evenCount){}
//Thefunctioncalloperatorprintswhetherthenumberis
//evenorodd.Ifthenumberiseven,thismethodupdates
//thecounter.
voidoperator()(intn)const{
cout<<n
if(n%2==0){
cout<<"iseven"<<endl
++m_evenCount
}else{
cout<<"isodd"<<endl

http://msdn.microsoft.com/en-us/library/dd293608.aspx

2/3

11/7/2014

Lambda Expressions in C++


}
}
private:
//DefaultassignmentoperatortosilencewarningC4512.
FunctorClass&operator=(constFunctorClass&)
int&m_evenCount//thenumberofevenvariablesinthevector.
}

intmain()
{
//Createavectorobjectthatcontains10elements.
vector<int>v
for(inti=1i<10++i){
v.push_back(i)
}
//Countthenumberofevennumbersinthevectorby
//usingthefor_eachfunctionandafunctionobject.
intevenCount=0
for_each(v.begin(),v.end(),FunctorClass(evenCount))
//Printthecountofevennumberstotheconsole.
cout<<"Thereare"<<evenCount
<<"evennumbersinthevector."<<endl
}

Output
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
There are 4 even numbers in the vector.

Summary
Lambdasareapowerfulandexpressiveprogrammingtechnique.Tolearnaboutthepartsandpropertiesofalambda,seeLambdaExpressionSyntax.Tolearnhowtouselambdasin
yourprograms,seeExamplesofLambdaExpressions.

SeeAlso
Reference
FunctionCall(C++)
for_each

Concepts
FunctionObjects

OtherResources
C++LanguageReference

CommunityAdditions
2014Microsoft

http://msdn.microsoft.com/en-us/library/dd293608.aspx

3/3

You might also like