iterate vector in reverse c++

To iterate over a vector in reverse in C++, you can use the rbegin() and rend() member functions of the vector class, along with a reverse iterator. Here's an example:

#include <iostream>
#include <vector>

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

    for (auto it = numbers.rbegin(); it != numbers.rend(); ++it) {
        std::cout << *it << " ";
    }

    return 0;
}

Explanation:

  1. We include the necessary headers for using vectors and the input/output stream (<iostream> and <vector>).

  2. Inside the main() function, we declare a vector called numbers and initialize it with some integer values.

  3. We use a for loop to iterate over the vector in reverse. The loop starts by initializing a reverse iterator it using the rbegin() function, which points to the last element of the vector.

  4. The loop condition it != numbers.rend() checks if the iterator has reached the rend() position, which is one position before the first element of the vector. If the condition is true, the loop continues; otherwise, it terminates.

  5. Inside the loop, we use the dereference operator * to access the value pointed to by the iterator, and we print it using std::cout.

  6. Finally, we return 0 to indicate successful execution of the program.

This code will output the elements of the vector in reverse order: 5 4 3 2 1.