What is the most effective way to get the index of an iterator of an std::vector?
I would prefer it - vec.begin()
precisely for the opposite reason given by Naveen: so it wouldn't compile if you change the vector into a list. If you do this during every iteration, you could easily end up turning an O(n) algorithm into an O(n^2) algorithm.
Another option, if you don't jump around in the container during iteration, would be to keep the index as a second loop counter.
Note: it
is a common name for a container iterator,std::container_type::iterator it;
.
I would prefer std::distance(vec.begin(), it)
as it will allow me to change the container without any code changes. For example, if you decide to use std::list
instead of std::vector
which doesn't provide a random access iterator your code will still compile. Since std::distance picks up the optimal method depending on iterator traits you'll not have any performance degradation either.