I have the following code:
int main()
{
vector<int> v;
for(int i = 0; i < 10; ++i)
v.push_back(i);
auto it = v.begin() + 3;
cout << "Iterator: " << *it << endl;
vector<int>::reverse_iterator revIt(it);
cout << "Reverse iterator: " << *revIt << endl;
}
After running this code I get the following output:
Iterator: 3
Reverse iterator: 2
Could someone explain why the 2 values differ ?
Reverse iterators ‘correspond’ to a
baseiterator with an offset of one element because of howrbegin()andrend()have to be represented using base iterators that are valid (end()andbegin()respectively). For example,rend()cannot be represented by an interator that ‘points’ before the container’sbegin()iterator, although that’s what it logically represents. Sorend()‘s ‘base iterator’ isbegin(). Therefore,rbegin()‘s base iterator becomesend().A reverse iterator automatically adjusts for that offset when it is dereferenced (using the
*or->operators).An old article by Scott Meyers explains the relationship in detail along with a nice picture: