tags:

views:

2265

answers:

4

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?

+7  A: 

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.

Daniel Earwicker
In fact the approach is passing by value, the compiler calls the copy constructor, and then swapping that newly created element. That is why rlbond suggests calling the copy constructor directly to achieve the same effect.
David Rodríguez - dribeas
+1  A: 

you should not use swap to copy vectors, it would change the "original" vector.

pass the original as a parameter to the new instead.

Raz
+5  A: 

This is another valid way to make a copy of a vector, just use its constructor:

std::vector<int> newvector(oldvector);

This is even simpler than using std::copy to walk the entire vector from start to finish to std::back_insert them into the new vector.

That being said, your .swap() one is not a copy, instead it swaps the two vectors. You would modify the original to not contain anything anymore! Which is not a copy.

X-Istence
+2  A: 

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);
rlbond