How to Reverse Iterate a Vector in C++?
Last Updated :
05 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 1, 2, 3, 4, 5, 6, 7, 8 };
for ( auto it = vec.rbegin(); it != vec.rend(); ++it) {
cout << *it << " " ;
}
cout << endl;
return 0;
}
|
Time Complexity : O(N) where N is the number of elements in vector
Auxilary Space : O(1)
Share your thoughts in the comments
Please Login to comment...