fast way to copy one vector into another


Question

I prefer two ways:

void copyVecFast(const vec<int>& original)
{
  vector<int> newVec;
  newVec.reserve(original.size());
  copy(original.begin(),original.end(),back_inserter(newVec));
}

void copyVecFast(vec<int>& original)
{

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

How do you do it?

1
135
7/20/2016 2:23:00 AM

Accepted Answer

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);
109
3/13/2009 9:30:36 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon