Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

Sasha picture Sasha · Mar 13, 2009 · Viewed 362.6k times · Source

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.

Answer

Daniel Earwicker picture Daniel Earwicker · Mar 13, 2009

They aren't the same though, are they? One is a copy, the other is a swap. Hence the function names.

My favourite is:

a = b;

Where a and b are vectors.