C++: Three Ways to Iterate the List/Array/Vector in Reverse Order


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.

1
2
3
4
5
6
7
8
9
10
11
#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;
}
#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):

1
2
3
4
5
6
7
8
9
10
11
#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;
}
#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.

1
2
3
4
5
6
7
8
9
10
11
12
13
#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;
}
#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) —

GD Star Rating
loading...
320 words
Last Post: Teaching Kids Programming - Sort List by Hamming Weight
Next Post: Teaching Kids Programming - Redistribute Characters to Make All Strings Equal

The Permanent URL is: C++: Three Ways to Iterate the List/Array/Vector in Reverse Order

Leave a Reply