Sign in to follow this  
yckx

iterator position in an stl container

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this