c++reverse-iterator

Reverse iterator not working as expected in C++


I was wondering why this code doesn't give 1 as output.

vector<int> myVector{1, 2, 3, 4, 6};
cout << *myVector.rend() << endl;

Output should be 1 but it gives random numbers.

But in this example everything is okay.

vector<int> myVector{1, 2, 3, 4, 6};
cout << *myVector.rbegin() << endl;

Output: 6


Solution

  • end() points to the memory location after the last element. Similarly, rend() points to memory location before the first element. They are supposed to be used as sentinel values ─ i.e. to iterate until that point is reached. So, to print 1, you should use:

    cout << *(myVector.rend()-1) << endl;