C++ vector::rend function

The C++ vector rend function returns a reverse_iterator that points to the position before the first element in a vector.

reverse_iterator rend();
const_reverse_iterator rend() const;

The first function returns read and write reverse_iterator that points to the position before the first position in the vector.Whereas the second function returns read only reverse_iterator.Note the iteration is done in reverse order.

First function:

Parameters:
none

Return type
reverse_iterator

Second function:

Parameters:
none

Return type
const_reverse_iterator

Consider the code below.The ‘vecRIt’ object will accept the reverse_iterator returned by rend( ) function.

vector<int> vec={ 23 , 45 , 9 , 10 } ;

vector<int>::reverse_iterator vecRIt =vec.rend( ) ;

The picture below shows the position pointed by ‘vecRIt’ object in the vector storage.

C++ Vector rend()

Since the iteration is done in the reverse order,to access the value using the reverse_iterator returned by the rend( ) function we will use negative index values instead of the normal +ve values.

The negativity of the indexes signify accessing the storage to the right of where the reverse_iterator points to.If we use a positive index value we will be accessing the storage to the left side of the iterator.In other words we will pointing to some invalid storage.

cout<< vecRIt[-1] << ” , ” << vecRIt[-2] << ” , ” << vecRIt[-3] << ” , ” << vecRIt[-4] ;

//Using the normal index value 
cout<< vecRIt[0] << ” , ” << vecRIt[1] << ” , ” << vecRIt[2] << ” , ” << vecRIt[3] ;

Output,

23 , 45 , 9 , 10
undefined value , undefined value , undefined value , undefined value

If you run the program in Visual Studio you will most likely get “Debug assertion Failed” message and in the middle you will see “Expression:vector iterator + offset out of range”.It simply means you have tried to acccess an invalid storage.




Leave a Reply

Your email address will not be published. Required fields are marked *