iterate vector from end to begin
To iterate over a vector in C++ from end to beginning, you can use a reverse iterator. Here are the steps to do this:
Declare a vector of the desired type. For example,
std::vector<int> myVector;
.Add elements to the vector using the
push_back()
function. For example,myVector.push_back(10);
.Use the
rbegin()
andrend()
functions of the vector to obtain reverse iterators that point to the last element and one past the first element, respectively. For example,auto it = myVector.rbegin();
.Create a loop using the reverse iterator. The loop should iterate from the last element to the first element. For example,
for (; it != myVector.rend(); ++it)
.Access the value of the current element using the dereference operator
. For example,
int value = it;
.Perform any desired operations with the element's value inside the loop.
Continue the loop until the iterator reaches
myVector.rend()
, which represents one position before the first element.
Here is an example of iterating over a vector from end to beginning:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
for (auto it = myVector.rbegin(); it != myVector.rend(); ++it) {
int value = *it;
std::cout << value << " ";
}
return 0;
}
Output:
30 20 10