[英]How to add a vector in reverse order with another vector in C++?
There is a vector vector<int>v
有一个向量
vector<int>v
I want to add another vector vector<int>temp
in reverse order with this vector.我想以与此向量相反的顺序添加另一个向量
vector<int>temp
。
For example,例如,
v = {1, 5, 7} and
temp = {11, 9, 8}
I want to add temp in reverse order, that is {8, 9, 11}
to vector v
.我想以相反的顺序添加 temp,即
{8, 9, 11}
到向量v
。
So that, v
will be : v = {1, 5, 7, 8, 9, 11}
因此,
v
将是: v = {1, 5, 7, 8, 9, 11}
Here's 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++ to do this ? STL 或 C++ 中是否有内置函数来执行此操作? or do i have to do it manually ?
还是我必须手动完成?
Use reverse iterators:使用反向迭代器:
std::vector<int> temp(v.rbegin(), v.rend());
Or std::reverse_copy()
:或
std::reverse_copy()
:
std::reverse_copy(v.begin(), v.end(), std::back_inserter(temp));
Try the following尝试以下
v.insert( v.end(), temp.rbegin(), temp.rend() );
Here is a demonstrative 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;
}
The program output is程序输出是
1 5 7 8 9 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.