vector rend call

Jul 14, 2019 at 12:56am
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;
}
Jul 14, 2019 at 1:52am
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 Jul 14, 2019 at 1:52am
Jul 14, 2019 at 4:45am
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 Jul 14, 2019 at 4:47am
Jul 14, 2019 at 5:43am
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 Jul 14, 2019 at 5:46am
Topic archived. No new replies allowed.