Iterate vector backwards in C++
In this tutorial, one can get to know how to iterate a vector from backward in C++. There are 3 methods to iterate a vector backward.
In arrays, if we wanted to increase or decrease the size, we must allocate space. But whereas in vectors, it can automatically add or decrease the size. In C++ STL, we have inbuilt iterators for a vector i.e. begin(), end(), rbegin(), rend(). These make our work very easy. Let’s see the 3 methods on how to iterate a vector backward.
Iterating vector backward
1. By ‘for’ loop:
This method is a basic one where we start from the rightmost element and come to the left element using a for loop.
2. By rbegin() and rend():
In this method, we use inbuilt functions to start reverse begin (rbegin) to reverse end.
3. By reversing the vector and iterating:
In this method, we reverse the whole array and iterate from starting.
Let’s see the code
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> arr = {1,2,3,4,5,6,7,8};
int n = arr.size();
// Method 1
cout << "Iterating vector backward using indexing" << endl;
for(int i=n-1; i>=0; i--){
cout << arr[i] << " ";
}
cout << endl;
// Method 2
cout << "\nIterating vector backward using rbegin and rend" << endl;
for (auto it = arr.rbegin(); it != arr.rend(); it++)
cout << *it << " ";
cout << endl;
// Method 3
cout << "\nReversing vector and iterating vector using begin() to end()" << endl;
reverse(arr.begin(), arr.end());
for (auto it = arr.begin(); it != arr.end(); it++)
cout << *it << " ";
return 0;
}Output
Iterating vector backward using indexing 8 7 6 5 4 3 2 1 Iterating vector backward using rbegin and rend 8 7 6 5 4 3 2 1 Reversing vector and iterating vector using begin() to end() 8 7 6 5 4 3 2 1
Complexity Analysis
Method 1: Time O(n), Space O(1)
Method 2: Time O(n), Space O(1)
Method 3: Time O(n), Space O(1)
Leave a Reply