Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 745
user83 Avatar asked Jun 01 '10 21:06

user83


4 Answers

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.

like image 79
fbrereto Avatar answered Nov 11 '22 12:11

fbrereto


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.

like image 35
Peter Avatar answered Nov 11 '22 12:11

Peter


std::ptrdiff_t index = std::distance(myDeque.begin(), curIterator);
like image 3
Matthew Flaschen Avatar answered Nov 11 '22 12:11

Matthew Flaschen


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

like image 2
Kornel Kisielewicz Avatar answered Nov 11 '22 13:11

Kornel Kisielewicz