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

I know historically it was better to use standard algorithms such as for_each

for loop instead of for

because they were more readable. But I just feel that as of C ++ 11, the regular loop is much more complicated than the numerous standard algorithms with their corresponding callback functors.

Am I wrong? Are many of the standard algorithms outdated? What are the different benefits offered by these approaches?

+3


source to share


2 answers


Use your opinion.

Many algorithms have become much easier to use in C ++ 11 thanks to lambdas and better bind expressions that allow you to define a functor fairly accurately. However, a for

range-based loop is also a perfectly legal option.



If you only need one or two statements in the body of the loop, then use a range based loop anyway. If you need to call a member function on a collection of objects, use for_each

and mem_fn

. If bind looks clear enough, use it. But no matter what you do, if you are rendering too much logic in one place, consider refactoring and give readable names to the smaller components of the work.

C ++ offers you many tools, and the existence of one tool does not mean that the other is useless. Large tool belts, like C ++, are aimed at power users, and experience will allow you to choose the right tool for the right job.

+2


source


This will be a rather subjective topic, but for what it's worth, I agree with you. I find it much better to use language constructs over library constructs, especially when the language construct is concise and readable. (Of course there was an argument for readability for_each

prior to C ++ 11 though)



+1


source







All Articles