user13812739
user13812739

Reputation:

begin() vs rbegin() how they are implemented?

In the following image I'm using the same type of iterators which means the same implementation of operator++ so how does the compiler know if it should get the next value or the previous one...?

enter image description here

Upvotes: 2

Views: 2435

Answers (1)

n314159
n314159

Reputation: 5095

First, the picture you have contains an error. As you can see here the reverse iterator type of vector is std::reverse_iterator<iterator> which uses the template std::reverse_iterator<T>. So begin and rbegin have not the same return value (and I also do not think they are convertible to each other).

But actually that wouldn't even be a problem, you could implement

struct iter {
    bool reverse;
    pointer ptr;
 
    iter& operator++() {
        if(reverse) --ptr;
        else ++ptr;
        return *this;
     }
};

But type-seperating them is really preferable.

Upvotes: 2

Related Questions