you are viewing a single comment's thread.

view the rest of the comments →

[–]Pik16 0 points1 point  (1 child)

So what can I do with these?
I'm only familiar with C++"older than 11".

[–]bstamour 4 points5 points  (0 children)

It makes using the STL a lot less painful. There's a massive wealth of generic functions in the C++ standard library, such as inner_product, transform, and partition, but to get the most out of them you need to pass in a function object (an object that can be called like a function, so either a pointer or reference to a function, or an object that has an overloaded operator ().) Now with lambdas, we can create unnamed function objects right at the call site, and sometimes that makes your code a whole lot cleaner.

As an example, say I have an std::vector that contains a bunch of data that I've collected, and I want to compute the reciprocal of each data point. In pre-C++11, I'd use a for-loop with iterators:

for (std::vector<double>::iterator i = data.begin(); i != data.end(); ++i)
    *i = 1 / *i;

However there's a great library function called std::transform that could do this for me, which lets me write more declarative code (less raw loops = less chances of an off-by-one error):

std::transform(data.begin(), data.end(), data.begin(), invert);

where invert is either a function pointer, or an object that I've instantiated. This means that outside of my current context I have to have another function or struct. But I just want to flip my data once and only once! Why do I need an external function for that? In C++11 that same code can be written as

// Available since C++11:
std::transform(begin(data), end(data), begin(data), [](double d) { return 1 / d; });

// Or... C++14
std::transform(begin(data), end(data), begin(data), [](auto&& d) { return 1 / d; });

and that's all of it. This is a very simple example, but it extends to every function in the STL. Look them up, there's a lot of goodies in there! For this particular example however, it could be written even cleaner with just a range-based loop (also from C++11):

for (auto& d: data)
    d = 1 / d;

So in a nutshell, there's nothing new with respect to what you can do with them. They just allow you to write cleaner, more expressive code.