Pages

std::transform

If we want to apply the same change to all the elements in a sequence, it is nice to use the std::transform algorithm. As usual, we pass to it a predicate that is delegate to perform the actual change.

If the transformation is not banal we usually write a functor to store the rule that has to be applied. At least, that's what we did when there was no boost or C++0x available.

In the example we see how to implement the transformation "increase the value by ten, than reduce the result by 5%" using boost::bind, and then with the C++0x lambda.

#include <iostream>
#include <list>
#include <functional>
#include <algorithm>
#include <iterator>

#include "boost/bind.hpp"

using namespace std;

namespace
{
template<class T>
void dump(list<T>& lst)
{
copy(lst.begin(), lst.end(), ostream_iterator(cout, " "));
cout << endl;
}

void init(list<double>& lst)
{
lst.clear();
lst.push_back(10.0);
lst.push_back(100.0);
lst.push_back(1000.0);
dump(lst);
}
}


void bind05()
{
list<double> values;

init(values);
auto fb = boost::bind(multiplies<double>(), 0.95, boost::bind(plus<double>(), _1, 10));
transform(values.begin(), values.end(), values.begin(), fb);
dump(values);

init(values);
auto fl = [](double d) { return (d + 10) * 0.95; };
transform(values.begin(), values.end(), values.begin(), fl);

dump(values);
}

Why using boost::bind when with C++0x lambda the code is so straigthforward? Well, maybe when you have to use a compiler that does not support C++0x yet.

The code is based on an example provided by "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. An interesting reading indeed.

No comments:

Post a Comment