c++ - append 到 STL 集合

标签 c++ c++11 vector stl append

因此,我在连接两个集合(例如,一个 std::vector 和一个 std::array)时一直这样做:

std::vector<Foo> foos;
std::array<Foo,12> toAdd = { /* value list */ };

for(....)
{
    foos.insert(end(foos),begin(toAdd),end(toAdd));
}

但是,我只是想到这样做:

template<typename T1, typename T2>
void append(T1 &target, T2 &source)
{
    target.insert(end(target),begin(source),end(source));
}


/// ....


append(foos,toAdd);

STL 中是否已经存在我没有遇到过的等效例程?

在这种情况下,toAdd 数组使用难以在代码中生成的特定值模式进行初始化,并且有点冗长。使用数组初始值设定项而不是大量的 ::push_back() 调用在代码中更加清晰。否则,我只是 vector::reserve() 来增加大小,然后将所有内容直接放入 vector 中。

最佳答案

也许最通用的方式是:

template <typename SrcCont, typename DestCont>
void append(const SrcCont& source, DestCont& destination) {
    std::copy(std::begin(source), std::end(source), std::back_inserter(destination));
}

例子:

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

template <typename SrcCont, typename DestCont>
void append(const SrcCont& source, DestCont& destination) {
    std::copy(std::begin(source), std::end(source), std::back_inserter(destination));
}

int main() {

  std::list<int> li{1, 2, 3};

  auto src = {4, 5, 6};

  append(src, li);

  for (int i : li)
    std::cout << i << '\n';
}

这打印:

1
2
3
4
5
6

关于c++ - append 到 STL 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21786979/

相关文章:

C++ 如何将数组 int[10] push_back 到 std::vector<int[10]>?

c++ - wchar_t 和 POSIX 库

c++ - C++ 中的意外循环行为

javascript - 从 C++ IHTMLInputElement 触发 onChange 事件

c++ - 构造 chrono::time_point

c++ - 排序 vector 上 std::lower_bound 的时间复杂度

c++ - 搜索多维 vector

c++ - 如何从二进制文件中读取 double 并将其保存在 vector 中

c++ - 当存在用户定义的移动分配运算符时,模板化的移动分配运算符被删除

c++ - 如何将元素添加到元组 vector