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
That would work, but an easier way is