How do I reverse a C++ vector?
Solution 1
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;
}
Solution 2
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
Solution 3
You can use std::reverse
like this
std::reverse(str.begin(), str.end());
Solution 4
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
Solution 5
You can also use std::list
instead of std::vector
. list
has a built-in function list::reverse for reversing elements.
Related videos on Youtube
Dollarslice
Updated on July 10, 2022Comments
-
Dollarslice almost 2 years
Is there a built-in vector function in C++ to reverse a vector in place?
Or do you just have to do it manually?
-
CashCow over 12 yearsthat doesn't however reverse the vector in-place. You could create a new vector with std::vector<T> v2( v1.rbegin(), v1.rend() ); v2.swap(v1); which would effectively use your solution. I don't see how it is more elegant or advantageous in any way to using std::reverse though.
-
Xeo over 12 years@CashCow: Well, for one, it's a no-op, it's O(1). Reversing.. not so much. Most of the time, you don't really need a reversed container, you only need to see it as reversed. In fact, I can't think of a situation where you actually need a reversed container that can't be solved with reverse iterators.
-
Sebastian Mach over 12 years@CashCow: Elegance is not always true elegance. In most cases in my professional career, I just needed a reversed view, but not a reversed vector. And in all those cases, performance would suffer totally needlessy if you'd create more copies or transform the ordering. Would you also
std::sort
a 1000 element vector, if you just need the top-10 in unspecified order, because it is more elegant thanstd::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. -
Nawaz over 10 years
print_range
is not correct: it will not work when empty range is passed. -
Vikas Goel over 8 yearsCould you explain how to reverse vector of vectors? I want v[0] to be swapped with v[v.size()-1] and the order of v[0][i] element remain as it is. This is similar to changing order of rows (if a vector is viewed as a Matrix). If a vector is defined as: vector<vector<int> > v; reverse(v.begin(), v.end()) doesn't reverse it. TIA!
-
Ivaylo Strandjev over 8 years@VikasGoel in fact the snippet you suggest should work. Maybe there is some other problem?
-
eozd almost 6 yearsstd::list should be preferred over vector in the only specific case of inserting many elements into arbitrary positions in the sequence. Using std::list over vector just because you will reverse the sequence is a bad idea performance-wise.
-
Orwellophile almost 5 yearsso the big question is, what will
std::reverse(a.rbegin(), a.rend())
do? ;^) -
Caleth over 4 yearsnitpick:
std::forward_list
is a container that doesn't haverbegin rend
-
Caleth over 4 years@Orwellophile the same as
std::reverse(a.begin(), a.end())
but with the arguments toswap
(viaiter_swap
) effectively switched -
Orwellophile about 4 years@caleth either sounds suspiciously like two
std::reverse
s make astd::forward
. the scary thing: that might even compile and function correctly. -
Caleth about 4 years@Orwellophile No, I mean that instead of
swap(first_element, last_element)
etc it'sswap(last_element, first_element)
-
Blastfurnace almost 4 yearsDoes this eight-year-old question need another duplicate answer that adds nothing?
-
billx over 2 years@Xeo an example where you actually need to compute the reversed vector is when you use an API whose implementation you cannot change.
-
Arthur Tacca about 2 yearsThis is the same as the answer by Ivaylo Strandjev, which is top voted and marked as accepted. Why did you post this?