user83
user83

Reputation: 83

In C++, how do I get an int index of an iterator?

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

Answers (4)

Kornel Kisielewicz
Kornel Kisielewicz

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

Peter
Peter

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

fbrereto
fbrereto

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

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

std::ptrdiff_t index = std::distance(myDeque.begin(), curIterator);

Upvotes: 4

Related Questions