iterator position in an stl container

Started by
2 comments, last by yckx 18 years, 9 months ago
Is there a way to get the position of an iterator to an stl container, specifically a std::string? I'm iterating through a string, and I need to know the index of the character I'm working with, and I would prefer to use the iterator itself to do this, rather than to keep and increment a separate index variable. Thanks. yckx
Advertisement
std::string iterators are random access, so you should just be able to subtract the begin() iterator from the iterator you have to get the index.
The more generic answer is the distance function in the <iterator> header. This should work on all the standard library iterators.

#include<iterator>..std::distance(vec.begin(), myiterator);


For a string, it simple does myiterator - vec.begin().

[smile]
Bah, I should have been able to think of that. Thanks for the tip, guys.

yckx

This topic is closed to new replies.

Advertisement