ChatGPT解决这个技术问题 Extra ChatGPT

How do I reverse a C++ vector?

Is there a built-in vector function in C++ to reverse a vector in place?

Or do you just have to do it manually?


L
Luc Touraille

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;
}

Could 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 > v; reverse(v.begin(), v.end()) doesn't reverse it. TIA!
@VikasGoel in fact the snippet you suggest should work. Maybe there is some other problem?
you can also keep the elements in reverse order, but then iterate backwards: for(auto i=a.end(); i!=a.begin();i--) {...} although that can be tricky due to off-by-one errors. so using rbegin() and rend() like others suggest is better
X
Xeo

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

that doesn't however reverse the vector in-place. You could create a new vector with std::vector 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.
@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.
@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 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.
so the big question is, what will std::reverse(a.rbegin(), a.rend()) do? ;^)
C
Chuck Norris

You can use std::reverse like this

std::reverse(str.begin(), str.end());

A
Arthur Tacca

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

the downside is that the elements are no longer contiguous in memory like a vector, so you can't use .data()
A
Ajay

You can also use std::list instead of std::vector. list has a built-in function list::reverse for reversing elements.


std::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.