Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a C-array to a vector in reverse order in C++98/03 without a for-loop

Tags:

c++

vector

Its pretty straightforward to append a C-array to a vector (in C++ 98/03) like so:

std::vector<int> vec;
const int array[5] = { 1 , 2 , 3 , 4 , 5};

vec.insert( vec.end() , array , array + 5 );

Is there a way to append the array to a vector in reverse order in C++98/03 without writing a for-loop. (Here's looking at you Sean Parent.)

like image 804
Olumide Avatar asked Aug 16 '17 10:08

Olumide


People also ask

How do you reverse the order of vectors?

To reverse a vector in R programming, call rev() function and pass given vector as argument to it. rev() function returns returns a new vector with the contents of given vector in reversed order.

How do I reverse the order of a vector in C++?

Given a vector, reverse this vector using STL in C++. Approach: Reversing can be done with the help of reverse() function provided in STL. The Time complexity of the reverse() is O(n) where n is the length of the string.

How do you add an array to a vector?

Insertion: Insertion in array of vectors is done using push_back() function. Above pseudo-code inserts element 35 at every index of vector <int> A[n]. Traversal: Traversal in an array of vectors is perform using iterators.


2 Answers

There you go. Use std::reverse_copy with std::back_inserter to add elements to the vector:

std::vector<int> vec;
int array[5] = { 1 , 2 , 3 , 4 , 5};

std::reverse_copy(array , array + 5, std::back_inserter(vec));

If you're concerned about performance, don't forget to reserve() before copying.

like image 82
The Quantum Physicist Avatar answered Oct 19 '22 01:10

The Quantum Physicist


vec.insert(std::end(vec),
           std::rbegin(array),
           std::rend(array));

Note that this uses C++14, but reverse iterators have been around much longer, you would just need to create them manually if stuck with an older standard:

int const a1[] = {1, 2, 3, 4, 5};
int a2[5];
std::copy(std::reverse_iterator<int const*>(std::end(a1)),
          std::reverse_iterator<int const*>(std::begin(a1)),
          std::begin(a2)); // copy in reverse

std::copy(std::begin(a2),
          std::end(a2),
          std::ostream_iterator<int>(std::cout, " ")); // prints "5 4 3 2 1 "
like image 20
BoBTFish Avatar answered Oct 19 '22 01:10

BoBTFish