【问题标题】:Combining two lists in C++在 C++ 中组合两个列表
【发布时间】:2017-07-22 11:03:02
【问题描述】:

如果我有两个列表 A 和 B,如何将 B 的所有元素添加到列表 A 的开头,而不“清空” B 列表。我基本上只想将 B 列表的副本转移到 A 列表的开头。我正在考虑使用 insert 并想仔细检查语法。

我知道如果我将它添加到末尾,它会是:

A.insert(A.end(), B.begin(), B.end());

所以在开头插入它会是:

A.insert(A.begin(), B.begin(), B.end());

??

【问题讨论】:

  • 你试过了吗?当你这样做时,它是有效的,还是出了什么问题?
  • 您可能需要在发布问题之前咨询documentation

标签: c++ list insert


【解决方案1】:

这可以通过一行来实现,使用列表可以双向迭代的事实。

copy(A.rbegin(), A.rend(), front_inserter(B));

完整示例(C++11 用于列表构造函数和打印代码,但答案是 C++03 有效):

#include <list>
#include <iterator>
#include <algorithm>
#include <iostream>

int main() {
  // Create lists
  std::list<char> A = {'a','b'};
  std::list<char> B = {'c','d'};

  // Insert A at the beginning of B
  copy(A.rbegin(), A.rend(), front_inserter(B));

  // Print result
  for(auto c : B)
    std::cout << c;
  std::cout << "\n";
  return 0;
}

【讨论】:

    【解决方案2】:

    制作要附加的列表的临时副本而不清空,然后将临时列表拼接到原始列表中。这是和示例。

    #include <iostream>
    #include <list>
    #include <vector>
    
    int main ()
    {
      std::list<int> mylist;
      std::list<int>::iterator it;
    
      std::list<int> otherList;
      std::list<int> combinedList;
    
      // set some initial values:
      for (int i=1; i<=5; ++i) mylist.push_back(i); // 1 2 3 4 5
      for (int i=6; i<=10; i++) otherList.push_back(i); // 6 7 8 9 10
    
      std::list<int> temp = otherList;
      combinedList = mylist;
      it = combinedList.begin();
    
      combinedList.splice(it, temp);
    
      std::cout << "mylist contains:";
      for (it=combinedList.begin(); it!=combinedList.end(); ++it)
        std::cout << ' ' << *it;
      std::cout << '\n';
    
      std::cout<<"orignal appended list:"<<std::endl;
      for(it=otherList.begin(); it!=otherList.end(); ++it)
        std::cout<<' '<<*it;
      std::cout<<'\n';
    
      return 0;
    }
    

    http://ideone.com/e.js/Ol6Wk1

    【讨论】:

      猜你喜欢
      • 2014-08-30
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      相关资源
      最近更新 更多