简体   繁体   中英

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM