Vector index from vector iterator

Jul 2, 2011 at 5:41pm
Hi

Is it possible to determine the vector index from the iterator which the find() function return in the code below..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v;
    std::vector<int>::iterator it;
    v.reserve(10);
    for(size_t i = 0; i < 10; i++)
        v.push_back(i);
 
    it = find(v.begin(), v.end(), 7);

    return 0;
}


Any suggestion or advice will be greatly appreciated!

Thanks.
Jul 2, 2011 at 5:49pm
Yes, distance(v.begin(),it) will get you the index. For random access iterators, you can use it-v.begin() (but that's already what distance does for those).
Jul 2, 2011 at 6:22pm
@Athar

Thanks a lot. Its very helpful to me.
Topic archived. No new replies allowed.