vector, get index from iterator

C

Christopher

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.
 
V

Victor Bazarov

Christopher said:
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
 
A

Andre Kostur

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) {
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top