Open In App

How to Traverse Vector Using const_reverse_iterator in C++?

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a vector can be traversed in reverse order using a const_reverse_iterator. A const_reverse_iterator is a type of iterator that points to the last element in the container and moves in the reverse direction. In this article, we will learn how to traverse a vector using a const_reverse_iterator in C++.

Example:

Input:
myVector = {1, 2, 3, 4, 5};

Output:
5 4 3 2 1

Traversing a Vector Using const_reverse_iterator in C++

To traverse a std::vector using a const_reverse_iterator, we can use the std::vector::crbegin() function to get a constant reverse_iterator pointing to the last element of the vector and the std::vector::crend() function to get a constant reverse_iterator pointing to one position before the first element of the vector.

We can then use the loop to increment these iterators to traverse the whole vector.

Note: const_reverse_iterator are generally used when we dont want to change the value stored in the vector.

C++ Program to Use a const_reverse_iterator with a Vector

C++




// C++ program to illustrate how to traverse a vector using
// a const_reverse_iterator
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Creating a vector
    vector<int> myVector = { 1, 2, 3, 4, 5 };
  
    // Getting a const_reverse_iterator to the beginning of
    // the reversed vector
    vector<int>::const_reverse_iterator it
        = myVector.crbegin();
  
    // Traversing the vector using the
    // const_reverse_iterator
    cout << "Traversing the vector in reverse order: ";
    while (it != myVector.crend()) {
        cout << *it << " ";
        ++it;
    }
    cout << endl;
  
    return 0;
}


Output

Traversing the vector in reverse order: 5 4 3 2 1 

Time Complexity: O(N), where N is the number of elements in the vector.
Auxiliary Sapce : O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads