What are the benefits of using for_each vs range-for?

advertisements

I know historically it was better to use standard algorithms such as for_each instead of a for loop because they were just more readable. But I just feel like with c++11 the regular for loop is far more terse than the numerous standard algorithms with their corresponding callback functors.

Am I wrong to think this? Are many of the standard algorithms obsolete? What are the different benefits offered by those approaches?


Use your judgement.

Many algorithms have become much easier to use in C++11 thanks to lambdas and better bind expressions, which allow you to specify the functor in a relatively concise fashion. However, the range-based for loop is a perfectly legitimate option, too.

If all you need is one or two statements in the loop body, then by all means use a range-based loop. If you need to call a member function on a collection of objects, maybe use for_each and mem_fn. If a bind expression looks clear enough, use it. But whatever you do, if you find yourself cramming too much logic into one place, consider refactoring and giving readable names to smaller components of work.

C++ offers you many tools, and the existence of one tool doesn't mean that another is useless. Large toolbelts, just like C++, target experienced users, and experience will let you choose the right tool for the right job.