When iterating over elements of a vector it is preferred to use iterators instead of an index (see Why use iterators instead of array indices?).
std::vector<T> vec;
std::vector<T>::iterator it;
for ( it = vec.begin(); it != vec.end(); ++it )
{
// do work
}
However, it can be necessary to use the index in the body of the loop. Which of the following would be preferable in that case, considering performance and flexibility/extensibility?
- Revert to the indexed loop
std::vector vec; size_t i; for ( i = 0; i < vec.size(); ++i ) { // use i }
- Calculate offset
std::vector vec; std::vector::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { size_t i = it - vec.begin(); // use i }
- Use std::distance
std::vector vec; std::vector::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { size_t i = std::distance( vec.begin(), it ); // use i }