All containers offer a reversed view of their content with rbegin()
and rend()
. These two functions return so-calles reverse iterators, which can be used like normal ones, but it will look like the container is actually reversed.
#include <vector>
#include <iostream>
template<class InIt>
void print_range(InIt first, InIt last, char const* delim = "\n"){
--last;
for(; first != last; ++first){
std::cout << *first << delim;
}
std::cout << *first;
}
int main(){
int a[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(a, a+5);
print_range(v.begin(), v.end(), "->");
std::cout << "\n=============\n";
print_range(v.rbegin(), v.rend(), "<-");
}
Live example on Ideone. Output:
1->2->3->4->5
=============
5<-4<-3<-2<-1