When you use an index to perform essentially sequential access to a container ( std::vector or something else), you impose a random access requirement on the underlying data structure, when in fact you do not need such access to your algorithm. The random access requirement is a pretty strong requirement compared to the much weaker sequential access requirement. Imposing a stronger requirement without good reason is a major design error.
So, the correct answer to your question is: use sequential (iterator) access when you can, use random (index) access only when you absolutely need it. Whenever possible, try to avoid access to the index.
If your algorithm relies critically on random access to the container, it becomes an external requirement of the algorithm. In this case, you can use access to the index without any reservations. However, if it is possible to implement the same algorithm using only iterators, it is recommended to stick to iterators only, i.e. Rely exclusively on sequential access.
Of course, the above rule, although true, makes sense only in the code, to a certain extent is general. If some other part of the code is so specific that you know for sure that the data structure you are working with is std::vector and will always be std::vector , then the access method no longer matters. Use whatever you prefer. However, I would still avoid accessing the index in situations where sequential access is sufficient.
source share