0

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.

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by Narue
3

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.

Votes + Comments
Well put, thank you.
Learned something new! cool!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.