>STL rocks

>I’ve just been writing a small article on the “gems of STL” and found that I really like what I’m seeing. A personal favorite is the transform operation (found in the functional header file). For example, lets do some adding.

#include <functional>
#include <list>

...

{
std::list<int> list;
list.push_back( ... ); // Populate

std::transform( list.begin(), list.end(), list.begin(), std::bind2nd( std::plus<int>(), 42 ) );
}

So, the transform method takes three iterators and an functor. The operators are, from the left, the starting point of the input, the end point of the input and the starting point of the output. The function simply specifies what to do with each list entry to create the output. In this case, std::plus takes two arguments, but we bind the second argument to 2. What this does is that it adds 42 to every item in the list (between begin and end), and replaces the original items (the results are placed from begin and onwards).

If you want the results to end up in another list, just use the back_inserter magical interator and point it to your results list.

{
std::list<int> list, res;
list.push_back( ... ); // Populate

std::transform( list.begin(), list.end(), std::back_inserter( res ), std::bind2nd( std::plus<int>(), 42 ) );
}

Quite readable and really cool code if you ask me.