Always use the variant that describes best what you intend to do. That is
For each element x in vec, do bar.process(x).
Now, let's examine the examples:
std::for_each(vec.begin(), vec.end(),
std::bind1st(std::mem_fun_ref(&Bar::process), bar));
We have a for_each there, too - yippeh. We have the [begin; end) range we want to operate on.
In principle, the algorithm was much more explicit and thus preferrable over any hand-written implementation. But then ... Binders? Memfun? Basically C++ interna of how to get hold of a member function? For my task, I don't care about them! Neither do I want to suffer from this verbose, creepy syntax.
Now the other possibility:
for (std::vector<Foo>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
bar.process(*it);
}
Granted, this is a common pattern to recognize, but ... creating iterators, looping, incrementing, dereferencing. These too are all things I don't care for in order to get my task done.
Admittedly, it looks waay better than the first solution (at least, the loop body is flexible and quite explicit), but still, it's not really that great. We'll use this one if we had no better possibility, but maybe we have ...
A better way?
Now back to for_each. Wouldn't it be great to literally say for_each and be flexible in the operation that is to be done, too? Fortunately, since C++0x lambdas, we are
for_each(v.begin(), v.end(), [&](const Foo& x) { bar.process(x); })
Now that we've found an abstract, generic solution to many related situations, it's worth noting that in this particular case, there is an absolute #1 favorite:
foreach(const Foo& x, vec) bar.process(x);
It really can't get much clearer than that. Thankfully, C++0x get's a similar syntax built-in!
map(bar.process, vec), although map for side effects is discouraged and list comprehensions/generator expressions are recommended over map). – delnan Jan 15 '11 at 11:03BOOST_FOREACH... – honk Jan 15 '11 at 13:40