Is there a more efficient way to do this?

vector<int> myvec;
vector<int>::iterator it;


// Count # of iterations
int i = 0;
while ( it != myvec.end() )

Just seems expensive to me.

Since it's a random access iterator, you can take the difference of the two to get the distance between them:

i = myvec.end() - it;

However, this requires a random access iterator. If you decide to change the container to a list, for example, the trick no longer works. The standard library supports a distance function in the <iterator> header that will do the right thing regardless of iterator type:

#include <iterator>


i = distance(it, myvec.end());

If the iterator type is random access, the difference trick will be used. Otherwise it falls back onto the less efficient looping methods.

commented: Well put, thank you. +2
commented: Learned something new! cool! +11