468,512 Members | 1,422 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

vector, get index from iterator

Seems odd, but I was wondering if I am in the middle of iterating
through a vector, is there a way to calc which index I am currently
on? something like: it - vec.begin()?

I don't want to change the loop to iterate through using indexes
instead of iterators, I just need the index for a little debug output,
the rest of the code in the loop uses the iterator.

thanks.
Nov 21 '07 #1
2 9147
Christopher wrote:
Seems odd, but I was wondering if I am in the middle of iterating
through a vector, is there a way to calc which index I am currently
on? something like: it - vec.begin()?
Absolutely! Since vector's iterators are of 'random access' kind,
the binary minus is defined for them to give the distance. For
all others you can use 'std::distance'.
I don't want to change the loop to iterate through using indexes
instead of iterators, I just need the index for a little debug output,
the rest of the code in the loop uses the iterator.
No need to justify yourself :-)

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 21 '07 #2
Christopher <cp***@austin.rr.comwrote in news:c6f679ff-5c3d-4af2-ac81-
18**********@f3g2000hsg.googlegroups.com:
Seems odd, but I was wondering if I am in the middle of iterating
through a vector, is there a way to calc which index I am currently
on? something like: it - vec.begin()?
That would work for vector... but a more general method would be:

std::distance(vec.begin(), it);

I don't want to change the loop to iterate through using indexes
instead of iterators, I just need the index for a little debug output,
the rest of the code in the loop uses the iterator.
Or, maintain the index as you are iterating through:

for (it = vec.begin(), i = 0; it != vec.end(); ++it, ++i) {
}

Nov 21 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

18 posts views Thread by Janina Kramer | last post: by
29 posts views Thread by Hagen | last post: by
6 posts views Thread by Joe | last post: by
5 posts views Thread by streamkid | last post: by
1 post views Thread by toton | last post: by
3 posts views Thread by chsalvia | last post: by
3 posts views Thread by JackC | last post: by
5 posts views Thread by Boltar | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.