Reputation: 83
I need to cout and return a deque element's index that an iterator is pointing to. How do I get an int out of an iterator?
Upvotes: 7
Views: 4378
Reputation: 57525
Out of the two presented methods:
std::ptrdiff_t index(std::distance(my_container.begin(), my_iterator));
and
std::ptrdiff_t index = some_iterator - some_deque.begin()
... the latter has the superiority of being only applicable to random access iterators -- hence when substituting for another container, you wont accidentaly get an expensive operation (O(n) for lists for example).
Upvotes: 2
Reputation: 7324
For random-access iterators you can just use subtraction:
size_t index = some_iterator - some_deque.begin()
Obviously this doesn't work for all iterators (eg. for std::list
or whatever) but I'd submit that there's a certain elegance in that you can only use this technique when it'll take constant time. If your container doesn't have random access iterators then it very probably isn't sensible to try to find the index of them anyway.
Upvotes: 8
Reputation: 35925
You can use:
std::ptrdiff_t index(std::distance(my_container.begin(), my_iterator));
Be aware of the runtime costs of such a routine, however- it depends on the data structure you use.
Upvotes: 9
Reputation: 284786
std::ptrdiff_t index = std::distance(myDeque.begin(), curIterator);
Upvotes: 4