How to Reverse Order a Vector

How to reverse order a vector?

You are almost there; rev does what you need:

rev(1:3)
# [1] 3 2 1
rev(numeric(0))
# numeric(0)

Here's why:

rev.default
# function (x)
# if (length(x)) x[length(x):1L] else x
# <bytecode: 0x0b5c6184>
# <environment: namespace:base>

In the case of numeric(0), length(x) returns 0. As if requires a logical condition, it coerces length(x) to TRUE or FALSE. It happens that as.logical(x) is FALSE when x is 0 and TRUE for any other number.

Thus, if (length(x)) tests precisely what you want - whether x is of length zero. If it isn't, length(x):1L has a desirable effect, and otherwise there is no need to reverse anything, as @floder has explained in the comment.

How do I reverse a C++ vector?

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

Copy a vector to another vector in reverse order

Simply just do this:

vector<int>n_v (v.rbegin(), v.rend());

Reversing a vector of strings without the reverse function

It's because you're swapping twice for each element.

For a vector of size of 4: Swap operations:

0 3
1 2
2 1
3 0

Loop over the half size of the vector.

for (int i = 0, j = names.size() - 1; i < names.size()/2; i++, j--)
{
std::string temp = names[i];
names[i] = names[j];
names[j] = temp;
}

Print the vector using another loop.

for (int i = 0; i < names.size(); i++)
{
cout<<names[i]<<endl;
}

Insert into vector in reverse order

You can use reverse iterators to iterate through parents like:

#include <iostream>
#include <vector>

int main() {
std::vector<int> parent1{1, 2, 3, 4, 5};
std::vector<int> parent2{6, 7, 8, 9, 0};

std::vector<int> child1;
std::vector<int> child2;

int cut = 2;
{
auto cut1 = std::begin(parent1); // set cut1 to element 1
auto cut2 = parent2.rbegin(); // set cut2 to element 0 (reverse)
std::advance(cut1, cut); // iterate cut1 to element 3
std::advance(cut2, cut); // iterate cut2 to element 8 (reverse)

child1.insert(child1.end(), cut1, std::end(parent1)); // copy elements 3, 4 ,5
child1.insert(child1.end(), parent2.rbegin(), cut2); // copy elements 0, 9 (reverse)
}
{
auto cut1 = parent1.rbegin(); // set cut1 to element 5 (reverse)
auto cut2 = parent2.begin(); // set cut2 to element 6
std::advance(cut1, parent1.size() - cut); // iterate cut1 to element 2 (reverse)
std::advance(cut2, parent2.size() - cut); // iterate cut2 to element 9

child2.insert(child2.end(), cut1, parent1.rend()); // copy elements 2, 1 (reverse)
child2.insert(child2.end(), parent2.begin(), cut2); // copy elements 6, 7, 8
}
for (const auto& el : child1) {
std::cout << el << " ";
}
std::cout << std::endl;
for (const auto& el : child2) {
std::cout << el << " ";
}
std::cout << std::endl;
return 0;
}

Since C++14 you can use std::rbegin(parent2) instead of parent2.rbegin().



Related Topics



Leave a reply



Submit