Copy a vector to another vector in reverse order
Asked Answered
F

3

10

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?

Fashionable answered 26/1, 2015 at 10:18 Comment(1)
This answer covers most variations on this theme, (Found by searching this site for "[c++] copy a vector in reverse order".)Duna
T
22

Simply just do this:

vector<int>n_v (v.rbegin(), v.rend());
Tiresome answered 26/1, 2015 at 10:19 Comment(0)
E
3

You may use reverse_iterator:

std::vector<int> n_v(v.rbegin(), v.rend());
Electroencephalogram answered 26/1, 2015 at 10:20 Comment(0)
F
2

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

Forrest answered 11/7, 2022 at 22:41 Comment(1)
There is now (C++23) std::ranges::to<std::vector>() to convert the range into vector.Electroencephalogram

© 2022 - 2024 — McMap. All rights reserved.