Dollarslice
Dollarslice

Reputation: 10284

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?

Upvotes: 233

Views: 296457

Answers (6)

Kacper Wyczawski
Kacper Wyczawski

Reputation: 431

The simplest way to reverse vector v is to use built-in C++ 20 function:

std::ranges::reverse(v);

Don't forget to #include <algorithm>.

Upvotes: 2

Arthur Tacca
Arthur Tacca

Reputation: 9988

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

Upvotes: 5

Hello W
Hello W

Reputation: 649

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

Upvotes: 0

Xeo
Xeo

Reputation: 131789

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

Upvotes: 57

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

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

Upvotes: 398

Chuck Norris
Chuck Norris

Reputation: 15190

You can use std::reverse like this

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

Upvotes: 31

Related Questions