将矢量追加到矢量的最佳方法

vde*_*ris 43 c++ vector append std c++11

std::vector<int> a;
std::vector<int> b;
std::vector<int> c;
Run Code Online (Sandbox Code Playgroud)

我想通过附加b's和c's元素来连接这三个向量a.哪种方法最好,为什么?


1)使用vector::insert:

a.reserve(a.size() + b.size() + c.size());
a.insert(a.end(), b.begin(), b.end());
a.insert(a.end(), c.begin(), c.end());
b.clear();
c.clear();
Run Code Online (Sandbox Code Playgroud)

2)使用std::copy:

a.reserve(a.size() + b.size() + c.size());
std::copy(b.begin(), b.end(), std::inserter(a, a.end()));
std::copy(c.begin(), c.end(), std::inserter(a, a.end()));
b.clear();
c.clear();
Run Code Online (Sandbox Code Playgroud)

3)使用std::move(from C++11):

a.reserve(a.size() + b.size() + c.size());
std::move(b.begin(), b.end(), std::inserter(a, a.end()));
std::move(c.begin(), c.end(), std::inserter(a, a.end()));
b.clear();
c.clear();
Run Code Online (Sandbox Code Playgroud)

Xaq*_*aqq 24

在我看来,你的第一个解决方案是最好的方法.

vector<>::insert 旨在添加元素,因此它是最合适的解决方案.

您可以调用reserve目标向量来保留一些空间,但除非您将大量向量添加到一起,否则它可能不会提供太多好处:vector<>::insert知道将添加多少元素,您将只避免一次reserve调用.

注意:如果那些vector类型更复杂(即自定义类,甚至是自定义类std::string),那么使用std::move可以为您提供良好的性能提升,因为它可以避免复制构造函数.int但是,对于矢量,它不会给你带来任何好处.

注2:值得一提的是,使用std::move会导致源vector的内容无法使用.


Mic*_*eyn 19

假设你想要复制而不是移动,这将是最好的方法:

a.reserve(a.size()+b.size()+c.size()); // Reserve space first
a.insert(a.end(),b.begin(),b.end());
a.insert(a.end(),c.begin(),c.end());
Run Code Online (Sandbox Code Playgroud)

如果你想搬家:

a.reserve(a.size()+b.size()+c.size()); // Reserve space first
a.insert(a.end(),std::make_move_iterator(b.begin()),
         std::make_move_iterator(b.end()));
a.insert(a.end(),std::make_move_iterator(c.begin()),
         std::make_move_iterator(c.end()));
b.swap(std::vector<int>()); // Clear and deallocate space
c.swap(std::vector<int>()); // Clear and deallocate space
Run Code Online (Sandbox Code Playgroud)

更新:您已经多次编辑了您的问题,使其成为一个移动目标.你的第一个选择现在与我的第一个建议非常相似.

更新2:从C++ 11开始,您可能不再需要使用"使用空向量交换"技巧来清除和释放空间,具体取决于您的库的实现vector.以下内容可以更直观的方式完成工作:

// Empty the vectors of objects
b.clear(); 
c.clear();

// Deallocate the memory allocated by the vectors 
// Note: Unlike the swap trick, this is non-binding and any space reduction
//       depends on the implementation of std::vector
b.shrink_to_fit();
c.shrink_to_fit();
Run Code Online (Sandbox Code Playgroud)

  • 你的例子给出了一个int的向量.如果你有一个指针向量,你可能需要考虑使用`std :: unique_ptr`或`std :: shared_ptr`来保存它们,具体取决于你的用例,以便处理正确的清理. (3认同)
  • `make_move_iterator` 的 +1:如果您有以后不打算使用的数据,请从中进行 `move`。 (2认同)