Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to iterate through a vector in reverse direction is by using the rbegin() and rend() functions, which return reverse iterators. Here is an example code snippet:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5};

    // iterating in reverse direction
    for (auto it = v.rbegin(); it != v.rend(); ++it) {
        cout << *it << " ";
    }

    return 0;
}

Output:

5 4 3 2 1

In the above code, we define a vector v of integers and initialize it with some values. We then use a for loop to iterate through the vector in reverse direction, starting from the last element and going up to the first element. The loop variable it is a reverse iterator that is initialized to v.rbegin() (which points to the last element) and is incremented until it reaches v.rend() (which points to one position before the first element). The *it expression dereferences the iterator and returns the value of the current element.