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.
#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
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Important Update of Delegation Service!
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- 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
Just vote for witness you but I have not enough sp... But of course I like your work. Thank you