Getting the Index of an Iterator

Method 1: Subtract the iterator from the beginning of the container

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    typedef std::vector<int> intvec;
    intvec vec(10);
    std::iota(vec.begin(), vec.end(), 0);
    for (intvec::const_iterator it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << " is at " << it - vec.begin() << "\n";
    }
}

Note that this will only work with a RandomAccessIterator.

Method 2: Use std::distance on the beginning of the container and the iterator

#include <list>
#include <algorithm>
#include <iostream>

int main()
{
    typedef std::list<std::string> stringlist;
    stringlist list;
    const char *words[] = {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};
    const size_t n = sizeof(words) / sizeof(const char*);
    std::copy(words, words + n, std::back_inserter(list));
    for (stringlist::const_iterator it = list.begin(); it != list.end(); ++it) {
        std::cout << *it << " is at " << std::distance(list.cbegin(), it) << "\n";
    }
}

This will work with any kind of iterator, but will be O(n) for a list iterator.
Notice the use of cbegin() to get a const iterator to the beginning. The iterator returned by begin() is non-const, and so cannot be compared to a const iterator by distance() as it’s a different type.

Related