vector rend call

I was expecting following program output 1.But for some reason I am getting output of "201360154".

int main ()
{
std::vector<int> bar = {1,2,3,4,5};
auto it = bar.rend();
std::cout<<*it;
return 0;
}
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>

int main ()
{
std::vector<int> bar = {1,2,3,4,5}; 
std::vector<int>::reverse_iterator it = bar.rend();
std::cout<<*(it-1);
return 0;
} 


1
Last edited on
No matter if you're using reverse iterators or not, it's always begin → end.
(The reverse end is not the beginning. Rather, it's one-past-the-beginning.)

To run through the range in forward order, iterate from begin() to end().
To run through the range in reverse order, iterate from rbegin() to rend().
Last edited on
About std::vector::rend....

Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (which is considered its reverse end).

You are retrieving a value that is outside your vector. Before the first element.

http://www.cplusplus.com/reference/vector/vector/rend/

cppreference has a nice graphic showing where end/rend point to:

https://en.cppreference.com/w/cpp/container/vector/rend
Last edited on
Topic archived. No new replies allowed.