Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Discovering lambda Functions

Finally, I want to show you a third way to iterate through a container (it is actually the second way that doesn't require an outside function). Having a background in math, I find this example—unlike the previous one—nothing short of beautiful and elegant. However, to make this work, you have to make use of the Boost library. Specifically, this example makes use of the lambda library within Boost, using a concept called lambda function.

A lambda function is a function that doesn't get named. So how can you possibly call a function if it doesn't have a name? (That sounds like a joke involving The Artist Once Again Known As Prince, but I'm serious.) Here's how: You code it right in place, where it would get called.

Although you've seen this concept many, many times, you probably don't think of it as a lambda function. Imagine a for loop like this:

for (int i=0; i<10; i++) { 
  somefunc(i); 
}

The loop calls a function somefunc with each iteration. But suppose that somefunc isn't very big and it doesn't get called anywhere else. It might be just this, for example:

void somefunc(int i) {
  cout << i << endl;
}

Chances are you wouldn't create a separate function for this cout stuff. Instead, you're more likely to code it right inside the for loop, like so:

for (int i=0; i<10; i++) { 
  cout << i << endl;
}

Now for the mental leap: Think of the stuff inside the braces as itself the code for a function that the for loop calls. Think of the code as an unnamed, in-place function. And the technical name for this kind of function is a lambda function.

Unfortunately, the built-in loop constructs in C++ are pretty much the only places where you'll see this kind of thing built into the language. Wouldn't it be nice to do such a thing with the for_each algorithm? Not to sound too much like a salesman, but (thanks to the Boost library) now you can! Good credit, bad credit, this approach can be yours for no money at all!

Before I show you some code, however, I want to explain something that will make your life a whole lot easier when using the lambda library. Although I don't have room here to fully describe it (check out the Boost site for the full docs), I will show you a couple things that will help you understand its gotchas.

First, remember that C++ fully supports operator overloading, through which you can do some pretty crafty things that give the illusion that you are extending the language. A really good example here is the endl function that you use in lines such as cout << endl;. Did I just say "function"? Why yes, I did. If you dig through the header files, you'll see that endl is a function (or more likely, a template function), and that there exists an operator overload for << that recognizes the cout type on the left and the endl function prototype on the right. The operator then calls the function on the right, such as endl, which writes out a newline. Pretty ingenious.

But what does that have to do with anything? Well, for my second point, remember that to successfully get the compiler to call your operator function, you must get the types of parameters exactly right. If you don't, the compiler won't match up your code to the operator function, and you'll get a compilation error.

Now hold those thoughts because after I show you how to use the lambda library, I'll show you how to be sure that the lambda library actually gets called when you want it to, instead of your code triggering that secret but infamous portion down in the compiler's bowels called print_compiler_error_to_harass_programmer().

Before showing you how to iterate through a map, I'll first demonstrate a slightly simpler version that iterates through a vector. Hold on to your suspenders, though, because I can tell you the first time I saw this, I stepped back and stood in awe—momentarily forgetting all the evils that permeate the world. Okay, maybe it wasn't that big a deal, but it was pretty cool. Here goes:

void demoVector() {
  vector<int> myvector;
  myvector.push_back(1);
  myvector.push_back(2);
  myvector.push_back(4);
  myvector.push_back(8);
  myvector.push_back(16);
  
  // Iterate and print using 
  // algorithm and lambda approach
  for_each(myvector.begin(), myvector.end(), 
    cout << _1 << '\n'
  );
}

First, make sure that you type _1 as a digit, not a letter: as underscore followed by 1. Now look carefully at the boldfaced line and notice that technically it's not an actual statement; rather, it's some bizarre thing being used as the third parameter to the for_each call. But it looks kind of like a statement, except that

  • it has no semicolon at the end (although there is one after the for_each call).
  • it has a strange _1 thingamabob in there.

This line of code runs for each item in the vector. The _1 is essentially a variable that takes on the value of the current item in the vector. Thus, with the first iteration, _1 contains 1. On the next iteration, it contains 2 and then 4 and then 8 and finally 16 (the numbers I pushed into the vector). Here's the output:

1
2
4
8
16

The lambda function, then, is the code that runs with each iteration:

cout << _1 << '\n'

But what is that thing, really? It's an expression containing operators that the compiler decodes; the code for these operators is in the lambda library. Here, the two operators are both <<. How does the compiler match this code up to the right operator code? The _1 is the key. And this is what I was getting at earlier: To trigger the correct operator, you have to have a correct type. Here, _1 is of a type from inside the lambda library, and that one little thing allows the compiler to match the first << operator up to the lambda library and, subsequently, the remaining << operators (in this case, there's only one more). Well, all righty then!

But what will happen if you take out the _1? Try it and see; change it to this:

cout << '\n'

When you do, you'll get some bizarre compiler errors. The compiler doesn't detect this as making use of the lambda library, and it dies immediately after choking and screaming at you a little to remind you whose fault it really is. (Sorry, as a former schoolteacher, that was insensitive; I shouldn't suggest my mistakes are actually my own. Let's blame it on the computer.)

And although this one manages to compile, it doesn't run correctly:

cout << "Hello " << _1 << '\n'

Thus, here's the basic rule for using the lambda library: As you write your lambda functions, you need to make sure that you have inserted into the function an operator or constant or function from the lambda library to trigger the correct operator. How do you know where to do it? The operators are evaluated from left to right, and each operator must have on its left or right side an item that will trigger the lambda operators. The result of the first operator is passed as the left operand to the second operator, and so on. That means if you get the very first operator to use the lambda library, you should be in good shape. If you don't use the _1 anywhere in that first operator, wrap your variables with a function call called var() or wrap your constants with constant(), like so:

for_each(myvector.begin(), myvector.end(), 
  cout << constant("Hello ") << "there\n"
);

This one works, even though it doesn't even use _1 anywhere. The function called constant triggers the lambda operators to kick in for that first << operator. After that, you're home free.

Well that's enough of the lambda library here; there's a whole world about it in the docs that goes way beyond what I've touched on here applied to iterators. In fact, the whole library contains what is essentially its own programming language, complete with its own looping constructs. Check it out; it's pretty cool.

  • + Share This
  • 🔖 Save To Your Account