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.)
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.
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.
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.
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.
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 "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With