Ask Your Question
0

How can a vector be iterated through in reverse direction?

asked 2023-05-16 19:12:18 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-16 19:27:02 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-16 19:12:18 +0000

Seen: 18 times

Last updated: May 16 '23