假设您要复制而不移动,那么这将是最好的方法:
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());
如果要移动:
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()); // Clear and deallocate space
c.swap(std::vector()); // Clear and deallocate space
更新:您已经对问题进行了数次编辑,使其成为一个移动的目标。 您的第一个选择现在与我的第一个建议非常相似。
更新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();