How to Reverse Iterate a Vector in C++? (original) (raw)
Last Updated : 23 Jul, 2025
In this article, we will learn different methods to iterate through the vector in reverse order in C++.
The most efficient method to iterate through the vector in reverse order is by using **reverse iterator. Let’s take a look at an example:
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector v = {1, 3, 4, 7, 9};
// Iterating the vector in reverse order
for (auto i = v.rbegin(); i != v.rend(); i++)
cout << *i << " ";
return 0;}
`
**Explanation: We used reverse iterator**vector rbegin()and **vector rend(). By iterating from rbegin() to rend(), we can print the elements of vector in reverse order.
There are also some other methods in C++ to iterate through the vector in reverse order. Some of them are as follows:
Table of Content
- Using Traditional Loop with Index
- Using Range Based Loop with Reverse Iterator
- Using for_each()
- Using reverse() Function with Loop
Using Index
A vector can be traverse in reverse order using for loop by starting from the last index and decrementing the index until we reach the first element.
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector v = {1, 3, 4, 7, 9};
// Iterating vector in reverse order
for (int i = v.size() - 1; i >= 0; i--)
cout << v[i] << " ";
return 0;}
`
Using a Temporary Reversed Vector
Create a temporary reversed vector using reverse iterator and then traverse it using range-based loop.
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector v = {1, 3, 4, 7, 9};
// Iterating the vector in reverse order
for (auto &i : vector<int>(v.rbegin(), v.rend()))
cout << i << " ";
return 0;}
`
Using reverse()
Reverse the vector using **reverse() function, traverse the vector normally and reverse the vector again after traversal.
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector v = {1, 3, 4, 7, 9};
// reverse the vector
reverse(v.begin(), v.end());
// Iterating through vector
for (auto i : v)
cout << i << " ";
return 0;}
`