Why can I not convert a reverse iterator to a forward iterator?

前端 未结 3 1506
情话喂你
情话喂你 2021-02-13 22:36

Well, I know why, it\'s because there isn\'t a conversion, but why isn\'t there a conversion? Why can forward iterators be turned to reverse iterators but not the other way roun

3条回答
  •  粉色の甜心
    2021-02-13 22:56

    You could write a helper function. One particularity of reverse_iterator is that base() gives a forward iterator that is next from the value that the reverse iterator dereferences to. This is because a reverse iterator physically points to the element after the one it logically points to. So to have the forward iterator to the same item as your reverse_iterator, you'll need to decrement the result of base() by one, or you could increment the reverse iterator first, then take the .base() of that.

    Both examples are shown below:

    #include 
    #include 
    #include 
    
    //result is undefined if passed container.rend()
    template 
    typename ReverseIterator::iterator_type make_forward(ReverseIterator rit)
    {
        return --(rit.base()); // move result of .base() back by one.
        // alternatively
        // return (++rit).base() ;
        // or
        // return (rit+1).base().
    }
    
    int main()
    {
        std::vector vec(1, 1);
        std::vector::reverse_iterator rit = vec.rbegin();
        std::vector::iterator fit = make_forward(rit);
        std::cout << *fit << ' ' << *rit << '\n';
    } 
    

    Warning: this behavior is different from that of the reverse_iterator(iterator) constructor.

提交回复
热议问题