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:
We include the necessary headers for using vectors and the input/output stream (
<iostream>
and<vector>
).Inside the
main()
function, we declare a vector callednumbers
and initialize it with some integer values.We use a for loop to iterate over the vector in reverse. The loop starts by initializing a reverse iterator
it
using therbegin()
function, which points to the last element of the vector.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.Inside the loop, we use the dereference operator
*
to access the value pointed to by the iterator, and we print it usingstd::cout
.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
.