Specifically for the type vector
iterate with for
normal controlling access is faster than through an iterator, but this is not true in most other existing data collections. Has to measure.
To access the element through the index, the collection needs to have a way to do this, it may not have, or it may be slow, so only the iterator will work or work better. The vector
obviously can access the index and is very fast.
The main reason to use an iterator is to give a better abstraction, demonstrate in the code that it is not only accessing elements by its index but going through it from beginning to end or the other way around. Then the iterator, in a vector
, may be preferred because it is more readable, or at least more concise. It also helps the fact that if in other cases it is better to use iterator, why only in those will cease to use? Standardize.
Will one day need to change vector
for another collection, if you write the code properly, few changes already solve the problem in a practical way. If you write the for
and the new collection that will replace the vector
not if it goes well with this form, or will have to change things, or worse, will not need to change anything, but the result will be the same, will have different commitments (performance for example) different.
You can take things on for
normal which may not be true. For example, it is common to use a int
to increase the content. Is it the most appropriate? When you choose the most concrete, you have to take a lot of care. Of course choosing the abstract needs others. In concrete need to know more about the collection used. What can be good in some scenarios, despite being worse in most. You have to use what is most suitable in each situation. Often concrete can be considered premature optimization.
Of course, the access by the index allows to "sweep" the vector
in less usual ways, although you can have some control over the iterator as well.
The iterator can give a little security or create a problem, depending on what will be done in the body. There are operations that will not be possible naturally using an iterator, but they may be possible if you modify some things, such as using a reference. Some operations that can be disastrous or at least harmful can be done without the programmer noticing, for example incrementing the iterator can create a new temporary iterator that is slower than normal.
The iterator can be shorter:
for (auto& elemento: vetor)
Some prefer to use even ready-made functions to iterate more abstractly yet. A std::algorithms
is your friend. The more abstract you tend to have less bugs.