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::vector
or 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::vector
and will always be a std::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.
Well when it comes to std::vector
I think using the subscript operator in a loop is just fine, and probably about the same in terms of performance. The advantage to using an iterator comes when you want to use the vector with other std
functions like in <algorithms>.
I don't think my argument is very strong but I almost always use the iterator version.
typedef std::vector<int> MyIndexes; // or whatever
MyIndexes indexes;
for (Something::iterator iter = indexes.begin(); iter != indexes.end(); ++iter);
Now if I have to change the vector to list or something similar I only have to change my typedef. This was useful on couple of occasions. auto keyword will make this better but I can't wait for C++0x for loop :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With