In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g.
for ( int i=0; i < vecVector.size(); i++ ) { .. }
Can anyone tell me why and in what cases I should use iterators and in what cases the code snippet above please?
Note that the usually implementation of vector won’t use an "int" as the type of the index/size. So your code will at the very least provoke compiler warnings.
Genericity
Iterators increase the genericity of your code.
For example:
Now, let’s imagine you change the vector into a list (because in your case, the list is now better). You only need to change the typedef declaration, and recompile the code.
Should you have used index-based code instead, it would have needed to be re-written.
Access
The iterator should be viewed like a kind of super pointer. It "points" to the value (or, in case of maps, to the pair of key/value).
But it has methods to move to the next item in the container. Or the previous. Some containers offer even random access (the vector and the deque).
Algorithms
Most STL algorithms work on iterators or on ranges of iterators (again, because of genericity). You won’t be able to use an index, here.