9

I am new in C++.
I need to copy a vector in reverse order to another vector.

Here's how i did it :

int temp[] = {3, 12, 17};

vector<int>v(temp, temp+3);

vector<int>n_v;

n_v=v;
reverse(n_v.begin(), n_v.end()); //Reversing new vector

Is there any simple way to copy a vector in reverse order to another vector in STL?

Black Swan
  • 93
  • 1
  • 3
  • [This answer](http://stackoverflow.com/questions/11019722/how-to-reverse-a-vector-of-strings-in-c/11019765#11019765) covers most variations on this theme, (Found by searching this site for "[c++] copy a vector in reverse order".) – molbdnilo Jan 26 '15 at 10:22

3 Answers3

21

Simply just do this:

vector<int>n_v (v.rbegin(), v.rend());
Ali Akber
  • 3,670
  • 3
  • 26
  • 40
2

You may use reverse_iterator:

std::vector<int> n_v(v.rbegin(), v.rend());
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

From C++20, the views can be used.

std::vector v = { 1,2,3,4,5,6,7,8 };
auto result = v | std::views::reverse ;

Here the result can be directly iterated 8 7 6 5 4 3 2 1.

But if still need a vector

std::vector rev_v(std::ranges::begin(result), std::ranges::end(result));

The advantage of these viewer adapters is, we can chain up multiple requirements.

For example, if the requirement says, reverse the vector, get the first four squaring them. We can do this in one statement.

auto result = v | std::views::reverse | std::views::take(4) | std::views::transform([](int i) { return i * i; });

The output is 64 49 36 25

Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34