STL iterators

Can I use iterators from STL as int type numbers?

Lets say I have a vector of some objects (like in a dictionary I have words). To access each element of that vector I can use the vector::iterator. But now I want to know which object this iterator corresponds to (to push the dictionary analogy further, I have numbered the words, found the word I've been looking for and now I want to know the corresponding number).

Is the only way to do that by embedding the ordering numbers in the objects them self?
For random access iterators you can use operator-:
uint index=yourIterator-vec.begin();

The more general variant that also works with other iterator types (mind the order):
uint index=std::distance(vec.begin(),yourIterator);
I think you want to use a std::map<int, someOtherType>, the iterator points to a std::pair with the key in first and the value in second.
Or else you store a std::pair<int, someOtherType> instead of someOtherType in your container if you don't want a std::map
Topic archived. No new replies allowed.