Shamilx
Shamilx

Reputation: 35

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

Upvotes: 0

Views: 187

Answers (3)

Johann Gerell
Johann Gerell

Reputation: 25591

In the same way that end() gives an invalid iterator "one item after the range", rend() gives an invalid iterator "one item before the range". So your first example outputs whatever semi-random data happens to be at that place in memory.

Upvotes: 0

Bharat S
Bharat S

Reputation: 364

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;

Upvotes: 4

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17444

"end" iterators are really "past the end" and not dereferencable, no matter whether they're forward or reverse.

BTW: Enable diagnostic mode for you C++ stdlib. It would have told you something's wrong. How you do that depends on the compiler and stdlib.

Upvotes: 0

Related Questions