My programming ramblings

C++11 lambda tutorial

Posted on November 1, 2011 by Paul

In my previous tutorials I’ve presented some of the newest C++11 additions to the language: regular expressions and raw strings. Another useful language addition is lambda, a lambda expression allows you to define and use anonymous functions inline (functions with a body but without a name). You can use a lambda expression instead of a function object, avoiding the need to create a separate class and a function definition. This is useful for example when you need a one-line expression to interact with many of the STL algorithms.

Lambda expressions are currently available in all major C++ compilers GCC, Visual Studio and Clang.

Let’s create a (useless) simple example of lambda expression that will return a number:

1 []()->int{return4;}();

Obviously the above code will do nothing visible (actually it will return an integer), we can use it to print 4 on the console:

1 intresult=[]()->int{return4;}();2 cout<<result<<endl;

A slightly more useful example that will receive as input an integer and will return twice this number:

Disclaimer:All data and information provided on this site is for informational purposes only. solarianprogrammer.com makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this site and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis. solarianprogrammer.com does not collect any personal information about its visitors except that which they provide voluntarily when leaving comments. This information will never be disclosed to any third party for any purpose. Some of the links contained within this site have my referral id, which provides me with a small commission for each sale. Thank you for understanding.