What is the most effective way to get the index of an iterator of an std::vector? explains how to do it for std::vector
or std::list
but what about std::map
?

- 1
- 1

- 25
- 2
2 Answers
The cleanest way to do this would be to use the std::distance
function:
auto index = std::distance(myMap.begin(), myMapItr);
However, this runs in O(n) time, which is inefficient for large maps.
If you need to determine the index of an iterator into a map or other ordered collection, you may want to search for a library containing an order statistic tree, which is a modified binary search tree that supports efficient (O(1) or O(log n)) time lookup of the index of a particular value in the tree.
Alternatively, if you are manually iterating over the tree, you can just keep a counter lying around alongside the iterator that you increment every time you traverse from one element to the next. This gives O(1)-time lookup of the index of the iterator, but is not fully general.
Hope this helps!

- 362,284
- 104
- 897
- 1,065
-
This is why I love this website. – user2512322 Jun 22 '13 at 19:51
Try this:
int IndexOf(Type *t)
{
Type** data = vector.data();
int index = 0;
while(*data++ != t)
{
index ++;
}
return index ;
}
-
-1 because this gets the index of a _value_ in a vector, not the equivalent index of an iterator (a position) in a map. – Jesse Chisholm Oct 17 '13 at 02:52