Loops on STL containers

C++ and STL are my everyday working tools. I have get used to use the same construction to iterate through the elements in an STL container:

I've seen most people use a for instead of a while loop:

I find the following reasons to prefer the first over the second option:
  1. The statement for the for loop is too large and usually need to be split into 2 (ugly) or 3 (same as while) lines.
  2. In the while option, operations are performed on the variable Object instead of the iterator itElement, yielding a cleaner and more readable coding style. This becomes a greater advantage when the container is a map instead of a vector.
  3. If some elements must be removed from the container, the for loop is simply not an option, whereas the while option is the way to go.

No comments:

Post a Comment