C++ STL – Vector in Reverse Order
Prerequisite: Vectors in C++
A vector can be printed in reverse order with the following methods:
- By traversing in the backward direction using indexing
- By traversing in the backward direction using begin() and end() functions in C++ STL
- By traversing in the backward direction using rbegin() and rend() functions in C++ STL
Examples:
Input: vector = {1, 2, 3, 4, 5}
Output: {5, 4, 3, 2, 1}
Input: vector = {10,5,20,15,25}
Output: {25, 15, 20, 5, 10}
1. Traversing the vector in a backward direction using indexing
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
cout << "Elements of vector in original order : " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
cout << "Elements of vector in reverse order : " ;
for ( int i = vec.size() - 1; i >= 0; i--)
cout << vec[i] << " " ;
return 0;
}
|
Output
Elements of vector in original order : 1 2 3 4 5
Elements of vector in reverse order : 5 4 3 2 1
2. Using begin() and end() functions
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
cout << "Elements of vector in original order : " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
cout << "Elements of vector in reverse order : " ;
for ( auto it = vec.end() - 1; it >= vec.begin(); it--)
cout << *it << " " ;
return 0;
}
|
Output
Elements of vector in original order : 1 2 3 4 5
Elements of vector in reverse order : 5 4 3 2 1
3. Using rbegin() and rend() function
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
cout << "Elements of vector in original order : " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
cout << "Elements of vector in reverse order : " ;
for ( auto it = vec.rbegin(); it != vec.rend(); it++) {
cout << *it << " " ;
}
return 0;
}
|
Output
Elements of vector in original order : 1 2 3 4 5
Elements of vector in reverse order : 5 4 3 2 1
Last Updated :
02 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...