Obtain an index into a vector using Iterators

c++, indexing, iterator, vector

Solution

If you're planning on using exclusively a vector, you may want to switch back to the indexed loop, since it conveys your intent more clearly than iterator-loop. However, if evolution of your program in the future may lead to a change of container, you should stick to the iterators and use std::distance, which is guaranteed to work with all standard iterators.

Problem

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 } ```

Original source

Related problems