How to add a vector in reverse order with another vector in C ++?

There is a vector vector<int>v
I want to add another vector vector<int>temp in the reverse order with this vector.

For instance,

  v = {1, 5, 7} and temp = {11, 9, 8} 

I want to add temp in reverse order, that is, {8, 9, 11} in the vector v .

So v will be: v = {1, 5, 7, 8, 9, 11}

Here is how I did it:

 int a[] = {1, 5, 7}; vector<int>v(a,a+3); int b[] = {11, 9, 8}; vector<int>temp(b,b+3); for(int i=temp.size()-1;i>=0;i--) v.push_back(temp[i]); for(int i=0;i<v.size();i++) cout<<v[i]<<" "; cout<<"\n"; 

Is there a built-in function in STL or C ++ for this? or do i need to do it manually?

+6
source share
2 answers

Use reverse iterators:

 std::vector<int> temp(v.rbegin(), v.rend()); 

Or std::reverse_copy() :

 std::reverse_copy(v.begin(), v.end(), std::back_inserter(temp)); 
+8
source

Try to execute

 v.insert( v.end(), temp.rbegin(), temp.rend() ); 

Here is a demo program

 #include <iostream> #include <vector> int main() { int a[] = { 1, 5, 7 }; std::vector<int> v( a, a + 3 ); int b[] = { 11, 9, 8 }; std::vector<int> temp( b, b + 3 ); v.insert( v.end(), temp.rbegin(), temp.rend() ); for ( int x : v ) std::cout << x << ' '; std::cout << std::endl; return 0; } 

Program exit

 1 5 7 8 9 11 
+2
source

Source: https://habr.com/ru/post/979955/


All Articles