• Advertisement
Sign in to follow this  

iterator position in an stl container

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
Bah, I should have been able to think of that. Thanks for the tip, guys.

yckx

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement