C++ lambda expressions

While watching a movie about STL I saw very interesting and uncommon structure in C++: lambda expressions.

What are lambda expressions? Actually, they are present in many scripting languages, to mention Python and Perl only. Lambda should actually be called anonymous functions, which means that we create a function which doesn’t have a name. What does it give to us? Well, in some cases we need a short, simple function to be used only once. There’s no need for creating new function – it will just mess our code. That’s why we have lambdas.

How do they look like in C++? In fact it’s very uncommon thing, many books mention it as a feature which shouldn’t be used. But in some cases it’s a very nice thing. Let’s have a look at example code:


#include <string>
#include <algorithm>
#include <vector>
using namespace std;

vector<string> sortMe;

int main()
{

// We add some elements to vector:
sortMe.push_back("Hi");
sortMe.push_back("Hello");
sortMe.push_back("Game");

// Now our task is to sort it according to the word length.
// To do this we will use sort() method from <algorithm>

sort(sortMe.begin(), sortMe.end(),
[](const string&amp; first, const string&amp; second)
{ return (first.size() < second.size() ) } );
return 0;
}

Let’s look at sort() method. Her 3rd argument is our lambda expression – anonymous function which compares two strings. We start with array brackets, indicating that we want to create new anonymous function. Then we specify what arguments it takes and body of it – like with a normal function. Compiler will generate inlined code for this function. Because of the fact that it doesn’t have a name we cannot use it in any different place in our code. But for such a task it’s very useful – we do not create new function, which would reside in our namespace, just simple inline anonymous call.

That’s all for today, good night 🙂

This entry was posted in C++ and tagged , , . Bookmark the permalink.

3 Responses to C++ lambda expressions

  1. Pingback: Alexander1

  2. Pingback: Alexander7

  3. Pingback: Jay

Leave a Reply