Whenever someone starts using the STL and they have a vector, you usually see:
vector<int> vec ;
//... code ...
for( vector<int>::iterator iter = vec.begin() ;
iter != vec.end() ;
++iter )
{
// do stuff
}
I just find that whole vector<int>::iterator syntax sickitating. I know you can typedef vector<int>::iterator VecIterInt, and that is slightly better..
But the question is, what’s wrong with good ol’:
for( int i = 0 ; i < vec.size() ; i++ )
{
// code
}
When you use index to perform essentially sequential access to a container (
std::vectoror anything else) you are imposing the random-access requirement onto the underlying data structure, when in fact you don’t need this kind of access in your algorithm. Random-access requirement is pretty strong requirement, compared to a significantly weaker requirement of sequential access. Imposing the stronger requirement without a good reason is a major design error.So the correct answer to your question is: use sequential (iterator) access whenever you can, use random (index) access only when you absolutely have to. Try to avoid index access whenever possible.
If your algorithm critically relies on the container being random-accessible, it becomes the external requirement of the algorithm. In this case you can use index access without any reservations. However, if it is possible to implement the same algorithm using iterators only, it is a good practice to stick to iterators only, i.e. exclusively rely on sequential access.
Of course, the above rule, while true, only makes sense in the code is generic to a certain degree. If some other portion of the code is so specific, that you know for sure that the data structure you are working with is a
std::vectorand will always be astd::vector, then the access method no longer matters. Use whatever you prefer. However, I would still avoid index access in situations when sequential access is perfectly sufficient.