假设我有2个标准向量:
vector<int> a;
vector<int> b;
Run Code Online (Sandbox Code Playgroud)
我们还说两者都有大约30个元素.
肮脏的方式将迭代通过b并通过添加每个元素vector<int>::push_back(),但我不想这样做!
我当时认为vector::insert()和std::copy()命令需要额外的分配.但是,如果我push_back()是一个新创建的元素,那么swap()我认为只要包含的类型没有使用默认构造函数分配,这将减少任何分配.
我的问题实际上是针对std::vectors类型的std::string,但应该适用于此处所述的其他包含类型:
template <typename T>
void appendMove(std::vector<T>& dst, std::vector<T>& src)
{
dst.reserve(dst.size() + src.size())
for(std::vector<T>::iterator it = src.begin(); it != src.end(); ++it)
{
dst.push_back(std::vector<T>());
std::swap(dst.end()[-1], *it);
}
}
Run Code Online (Sandbox Code Playgroud)
我对么?我错过了什么吗?也许还有更好的方法吗?