0

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?

Community
  • 1
  • 1

2 Answers2

2

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
-1

Try this:

int IndexOf(Type *t)
{
    Type** data = vector.data();

    int index = 0;

    while(*data++ != t)
    {
        index ++;
    }

    return index ;
}