There's a function std::reverse
in the algorithm
header for this purpose.
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a;
std::reverse(a.begin(), a.end());
return 0;
}
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
std::sort
a 1000 element vector, if you just need the top-10 in unspecified order, because it is more elegant than std::partition
? This is the school of thought that cripples my PC experience today as it did 15 years ago, with the difference that yet more cycles are wasted, billions of them.
print_range
is not correct: it will not work when empty range is passed.
std::reverse(a.rbegin(), a.rend())
do? ;^)
You can use std::reverse
like this
std::reverse(str.begin(), str.end());
Often the reason you want to reverse the vector is because you fill it by pushing all the items on at the end but were actually receiving them in reverse order. In that case you can reverse the container as you go by using a deque
instead and pushing them directly on the front. (Or you could insert the items at the front with vector::insert()
instead, but that would be slow when there are lots of items because it has to shuffle all the other items along for every insertion.) So as opposed to:
std::vector<int> foo;
int nextItem;
while (getNext(nextItem)) {
foo.push_back(nextItem);
}
std::reverse(foo.begin(), foo.end());
You can instead do:
std::deque<int> foo;
int nextItem;
while (getNext(nextItem)) {
foo.push_front(nextItem);
}
// No reverse needed - already in correct order
You can also use std::list
instead of std::vector
. list
has a built-in function list::reverse for reversing elements.
Success story sharing