通过保留和复制,还是通过创建和交换来复制向量更有效?

2021-12-21 00:00:00 algorithm vector c++ stl

我正在尝试有效地制作矢量的副本.我看到两种可能的方法:

I am trying to efficiently make a copy of a vector. I see two possible approaches:

std::vector<int> copyVecFast1(const std::vector<int>& original)
{
  std::vector<int> newVec;
  newVec.reserve(original.size());
  std::copy(original.begin(), original.end(), std::back_inserter(newVec));
  return newVec;
}

std::vector<int> copyVecFast2(std::vector<int>& original)
{
  std::vector<int> newVec;
  newVec.swap(original);
  return newVec;
}

以下哪个是首选,为什么?我正在寻找最有效的解决方案,以避免不必要的复制.

Which of these is preferred, and why? I am looking for the most efficient solution that will avoid unnecessary copying.

推荐答案

如果您通过引用发送参数,您的第二个示例将不起作用.你的意思是

Your second example does not work if you send the argument by reference. Did you mean

void copyVecFast(vec<int> original) // no reference
{

  vector<int> new_;
  new_.swap(original); 
}

那行得通,但更简单的方法是

That would work, but an easier way is

vector<int> new_(original);

相关文章