C++ vector::rend() usage with example

In C++, the standard library provides us with vectors, which are dynamic arrays. It consists of multiple homogeneous objects, which can be accessed by their position in the vector. It is automatically resized (if needed). The vector::rend() is a C++ Standard Library function which returns a reverse iterator pointing to the imaginary element preceding the first element in the vector.

Note:
Adding an offset to a reverse iterator moves it in the opposite direction i.e. towards the left
Subtracting an offset moves it towards the right

Syntax:

vector_name.rend()

Parameter: The vector::rend() function does not accept any parameter.
Return value: The vector::rend() function returns a reverse iterator to the imaginary element preceding the first element.

Example of vector::rend() function

#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> vec;

  for(int i=1;i<=5;i++)
    vec.push_back(i);

  cout<<"Vector in normal order: ";
  for(vector<int>::iterator it=vec.begin();it!=vec.end();++it)
    cout<<*it<<"  ";
  cout<<endl;


  cout<<"Vector in reverse order: ";
  for(vector<int>::reverse_iterator it=vec.rbegin();it!=vec.rend();++it)
    cout<<*it<<"  ";
  cout<<endl;

  vector<int>::reverse_iterator it=vec.rend();
  cout<<"Value pointed by offset 2 is: "<< *(it-2);

}

Output:

Vector in normal order: 1  2  3  4  5
Vector in reverse order: 5  4  3  2  1
Value pointed by offset 2 is: 2

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

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

Scroll to Top