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++
// C++ STL program to print all elements // of a vector in reverse order #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);
// Printing original order
cout << "Elements of vector in original order : " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
// Printing all elements in reverse order
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++
// C++ STL program to print all elements // of a vector in reverse order #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);
// Printing original order
cout << "Elements of vector in original order : " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
// Printing all elements in reverse order
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++
// C++ STL program to print all elements // of a vector in reverse order #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);
// Printing original order
cout << "Elements of vector in original order : " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
// Printing all elements in reverse order
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