Is it more efficient to copy a vector by reserving and copying, or by creating and swapping? [duplicate]
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.
Solution 1:
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.
Solution 2:
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);