C++ Standard Library C++ STL Library

C++ <vector> - rbegin() Function



The C++ vector::rbegin function returns the reverse iterator pointing to the last element of the vector. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the vector container. Similarly, decreasing a reverse iterator results into moving to the end of the vector container. Please note that, Unlike the vector::back function, which returns a direct reference to the last element, it returns the reverse iterator pointing to the same element of the vector.

C++ rbegin rend

Syntax

reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;

Parameters

No parameter is required.

Return Value

A reverse iterator to the reverse beginning of the sequence container. If the sequence object is constant qualified, the function returns a const_reverse_iterator, else returns an reverse_iterator.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::rbegin function returns the reverse iterator pointing to the last element of the vector MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<string> MyVector{"Alpha","Coding","Skills"};
  vector<string>::reverse_iterator rit;

  rit = MyVector.rbegin();
  cout<<*rit<<" ";
  rit++;
  cout<<*rit<<" ";
  rit++;
  cout<<*rit<<" ";
  return 0;
}

The output of the above code will be:

Skills Coding Alpha 

Example:

Lets see another example where the vector called MyVector contains integer values and vector::rbegin function is used with vector::rend function to specify a range including all elements of the vector container.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};
  vector<int>::reverse_iterator rit;

  for(rit = MyVector.rbegin(); rit != MyVector.rend(); ++rit)
    cout<<*rit<<" ";

  return 0;
}

The output of the above code will be:

50 40 30 20 10 

❮ C++ <vector> Library