To iterate over a vector in reverse order in C++, you can use a reverse iterator along with the rbegin()
and rend()
member functions of the vector.
In this example,
numVec
containing several numeric values.rit
initialized to numVec.rbegin()
, which points to the last element of the vector.rit
to numVec.rend()
, which points to one position before the beginning of the vector.rit
, effectively traversing the vector in reverse order.#include <iostream>
#include <vector>
int main() {
std::vector<int> numVec = {10, 20, 30, 40, 50};
for (auto rit = numVec.rbegin(); rit != numVec.rend(); ++rit) {
std::cout << *rit << std::endl;
}
return 0;
}
50 40 30 20 10
In this example,
strVec
containing several string values.rit
initialized to strVec.rbegin()
, which points to the last string element of the vector.rit
to strVec.rend()
, which points to one position before the beginning of the vector.rit
, effectively traversing the vector in reverse order.#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> strVec = {"apple", "banana", "cherry", "date"};
for (auto rit = strVec.rbegin(); rit != strVec.rend(); ++rit) {
std::cout << *rit << std::endl;
}
return 0;
}
date cherry banana apple
In this tutorial, we learned How to Iterate Over a Vector in Reverse Order in C++ language with well detailed examples.