【问题标题】:How to add a vector in reverse order with another vector in C++?如何在 C++ 中将一个向量与另一个向量以相反的顺序添加?
【发布时间】:2015-02-18 18:31:05
【问题描述】:

有一个向量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++ 中是否有内置函数来执行此操作?还是我必须手动完成?

【问题讨论】:

  • temp (v.rbegin(), v.rend()) 反向迭代器 FTW

标签: c++ algorithm vector stl


【解决方案1】:

使用反向迭代器:

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

std::reverse_copy():

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

【讨论】:

    【解决方案2】:

    试试下面的

    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 
    

    【讨论】:

    • 在我的机器上工作(使用 g++ -std=c++11。谢谢。注意:另一个示例也可以,但我必须包含 来编译它。您的示例使用只有一种复制方法(即vector::insert),这与我的特定样式要求兼容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    相关资源
    最近更新 更多