If you frequently use other algorithms from the STL, there are several advantages to for_each
:
- It will often be simpler and less error prone than a for loop, partly because you'll be used to functions with this interface, and partly because it actually is a little more concise in many cases.
- Although a range-based for loop can be even simpler, it is less flexible (as noted by Adrian McCarthy, it iterates over a whole container).
Unlike a traditional for loop, for_each
forces you to write code that will work for any input iterator. Being restricted in this way can actually be a good thing because:
- You might actually need to adapt the code to work for a different container later.
- At the beginning, it might teach you something and/or change your habits for the better.
- Even if you would always write for loops which are perfectly equivalent, other people that modify the same code might not do this without being prompted to use
for_each
.
Using for_each
sometimes makes it more obvious that you can use a more specific STL function to do the same thing. (As in Jerry Coffin's example; it's not necessarily the case that for_each
is the best option, but a for loop is not the only alternative.)