Sign in to follow this  

Given a Iter how to know index of vector?

This topic is 4352 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If you want to be able to work with just about any type of iterator, not just random access iterators, you can use the std::distance function, found in <iterator>
Quote:
MSDN
template<class Init, class Dist>
ptrdiff_t distance(InIt first, InIt last);

The template function sets a count n to zero. It then effectively advances first and increments n until first == last. If InIt is a random-access iterator type, the function evaluates the expression n += last - first. Otherwise, it performs each iterator increment by evaluating ++first.

So it would look something like:
int index = std::distance(v.begin(), iter);

Share this post


Link to post
Share on other sites
Quote:
Original post by Mushu
You should be able to do some nifty iterator arithmatic (someone will correct me if I'm wrong) -

int index = iter - vector.begin();


This is what I do. You can also do things like
iter + 5

to find the element five beyond the iterator. Very useful.

Share this post


Link to post
Share on other sites
Quote:
Original post by Agony
If you want to be able to work with just about any type of iterator, not just random access iterators, you can use the std::distance function, found in <iterator>
Quote:
MSDN
template<class Init, class Dist>
ptrdiff_t distance(InIt first, InIt last);

The template function sets a count n to zero. It then effectively advances first and increments n until first == last. If InIt is a random-access iterator type, the function evaluates the expression n += last - first. Otherwise, it performs each iterator increment by evaluating ++first.

So it would look something like:
int index = std::distance(v.begin(), iter);


This has the disadvantage of being more verbose. It also has the advantage of being applicable to a wider range of iterator types (so your code will still work when you change the vector to a list instead, just slower for that operation). It does not have the disadvantage of being slower, because of the tag dispatching for random-access iterators that is mentioned (and because the compiler will apply the usual further optimizations anyway such as inlining).

Share this post


Link to post
Share on other sites

This topic is 4352 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this