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.
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
Asked: 2023-05-16 19:12:18 +0000
Seen: 18 times
Last updated: May 16 '23
How can I change the direction to RTL in DaisyUI when switching the language to RTL?
How to give an <svg> element a double border using CSS when there is no style attribute present?
Why does the fixed position interfere with the functionality of overflow hidden?
How can I customize the Swiper Element v9 in ionic 6 with stylish design?