Vector rbegin( ) and rend( ) function in C++

In this tutorial, we will understand how to use rbegin( ) and rend( ) functions in C++ STL.

In C++, we have vectors that can automatically add or decrease the size which doesn’t require memory allocation by the user. Vector has inbuilt iterators i.e. begin( ), end( ), rbegin( ), rend( ), cbegin( ), cend( ).

begin( ) – it points to the starting of the vector
end( ) – it points to end of the vector
rbegin( ) – it points to the reverse starting of the vector (i.e. ending)
rend( ) – it points to reverse end of the vector (i.e. starting)
cbegin( ) – constant iterator which points to the starting of the vector
cend( ) – constant iterator which points to end of the vector

Let’s see the code

#include <bits/stdc++.h>
using namespace std;

int main(){

    vector<int> arr = {1,2,3,4,5,6,7,8};

    cout << "Iterating vector backward using rbegin and rend" << endl;
    for (auto it = arr.rbegin(); it != arr.rend(); it++)
        cout << *it << " ";

    return 0;
}

Output

Iterating vector backward using rbegin and rend
8 7 6 5 4 3 2 1

 

Complexity Analysis

Time: O(n) -> for iterating whole vector
Space: O(1)

Leave a Reply

Your email address will not be published.