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() )
{
    ++it;
    ++i;
}

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: Learned something new! cool! +11
commented: Well put, thank you. +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.