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.
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.