Open In App

How to Reverse Iterate a Vector in C++?

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

In C++, vectors are dynamic arrays that provide random access so they can be iterated in both directions i.e. from beginning to end and end to the beginning. In this article, we will discuss how to reverse iterate a vector in C++.

Example

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

Output:
myVector = { 8, 7, 6, 5, 4, 3, 2, 1 }

Iterate a Vector in Reverse Order

In C++ containers, reverse iterators are used to iterate through a container in reverse order. The std::vector::rbegin() and std::vector::rend() member functions of the std::vector class can be used to iterator the vector in reverse order.

C++ Program to Iterate a Vector in Reverse Order

C++




// C++ Program to Display Vector Elements in Reverse Order
// Using Reverse Iterator
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Declare and initialize a vector
    vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8 };
  
    // Use a reverse iterator to display vector elements in
    // reverse order
    for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
        cout << *it << " ";
    }
    cout << endl;
  
    return 0;
}


Output

8 7 6 5 4 3 2 1 

Time Complexity : O(N) where N is the number of elements in vector
Auxilary Space : O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads