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:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> 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;
}
Output
9 7 4 3 1
Explanation: We used reverse iteratorvector 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 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.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> 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;
}
Output
9 7 4 3 1
Using a Temporary Reversed Vector
Create a temporary reversed vector using reverse iterator and then traverse it using range-based loop.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> 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;
}
Output
9 7 4 3 1
Using reverse()
Reverse the vector using reverse() function, traverse the vector normally and reverse the vector again after traversal.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> 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;
}
Output
9 7 4 3 1