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?
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.
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.
std::ptrdiff_t index = std::distance(myDeque.begin(), curIterator);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With