# Given a Iter how to know index of vector?

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

## Recommended Posts

vector<int> v; v.push_back(4); v.push_back(32); ..... v.push_back(41); iter = min_element(v.begin(), v.end() ); according to iter, how to know index of iter? if *iter = 32 I know index is 1 that is v[1].

##### Share on other sites
You should be able to do some nifty iterator arithmatic (someone will correct me if I'm wrong) -

int index = iter - vector.begin();

##### Share on other sites
iter - v.begin();

##### Share on other sites
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:
 MSDNtemplate 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 on other sites
Quote:
 Original post by MushuYou 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 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:
 MSDNtemplate 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).

1. 1
2. 2
3. 3
Rutin
20
4. 4
khawk
14
5. 5

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633655
• Total Posts
3013186
×