Advantages of std::for_each over for loop

后端 未结 21 729
遥遥无期
遥遥无期 2020-11-29 15:23

Are there any advantages of std::for_each over for loop? To me, std::for_each only seems to hinder the readability of code. Why do then some coding

21条回答
  •  孤独总比滥情好
    2020-11-29 16:04

    If you frequently use other algorithms from the STL, there are several advantages to for_each:

    1. 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.
    2. 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).
    3. 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:

      1. You might actually need to adapt the code to work for a different container later.
      2. At the beginning, it might teach you something and/or change your habits for the better.
      3. 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.
    4. 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.)

提交回复
热议问题