c++stliteratorcontainersreverse-iterator

calculate std::distance between two std::reverse_iterators


I have a code snippet like this:

int* array = new int[size];
std::reverse_iterator<int*> it2 = ... // arbitrary in array

How can i compute the distance between last and it2? I tried this, but it gives back zero:

std::distance(std::reverse_iterator<int*>(array + size), it2);

Solution

  • Your approach to computing the distance looks correct to me. Certainly, this prints 10 when using gcc or clang:

    #include <algorithm>
    #include <iostream>
    #include <iterator>
    
    int main()
    {
        const int size = 20;
        int* array = new int[size];
        std::cout << "distance="
                  << std::distance(std::reverse_iterator<int*>(array + 20),
                                   std::reverse_iterator<int*>(array + 10))
                  << '\n';
        delete[] array;
    }