Given a list/array/vector in C++, we can iterate the elements in the reversed order using the following approaches:
Traditional Way, Iterate by Index
We can iterate by index, the only pitfall is that the .size() is size_t which is usually unsigned integer, thus we need to static_cast it into int before we subtract one.
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> data({1, 2, 3, 4, 5});
for (int i = static_cast<int>(data.size()) - 1; i >= 0; -- i) {
cout << data[i] << endl;
}
return 0;
}
STL: the rbegin and rend
We can use the STL iterators to iterate from rbegin (reversed begin) to rend (reversed end):
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> data({1, 2, 3, 4, 5});
for (auto it = rbegin(data); it != rend(data); it ++) {
cout << *it << endl;
}
return 0;
}
Iterate using the reverse_iterator
Another STL approach is to use the reverse_iterator and then moving the iterator one by one until it reaches rend. Please note that the iterator needs to be plus one.
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> data({1, 2, 3, 4, 5});
vector<int>::reverse_iterator pt = rbegin(data);
while (pt != rend(data)) {
cout << *pt << endl;
pt ++;
}
return 0;
}
–EOF (The Ultimate Computing & Technology Blog) —
303 wordsLast Post: Teaching Kids Programming - Sort List by Hamming Weight
Next Post: Teaching Kids Programming - Redistribute Characters to Make All Strings Equal