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

in #programming5 years ago

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) --

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

Just vote for witness you but I have not enough sp... But of course I like your work. Thank you

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.081
BTC 59524.83
ETH 1569.75
USDT 1.00
SBD 0.42