Olumide Olumide - 1 year ago 302
C++ Question

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

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 Scott Parent.)

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download