如何在C ++中使用另一个向量以相反的顺序添加向量?

时间:2014-12-19 19:16:19

标签: c++ vector stl

有一个向量vector<int>v
我想用这个向量以相反的顺序添加另一个向量vector<int>temp

例如,

   v = {1, 5, 7} and

temp = {11, 9, 8}

我想以相反的顺序添加temp,即{8, 9, 11}向量v

这样,v将是:v = {1, 5, 7, 8, 9, 11}

以下是我的表现:

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";

STL或C ++中是否有内置函数来执行此操作?或者我必须手动完成吗?

2 个答案:

答案 0 :(得分:9)

使用反向迭代器:

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

std::reverse_copy()

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

答案 1 :(得分:4)

尝试以下

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

这是一个示范程序

#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;
}

程序输出

1 5 7 8 9 11