Copying std::vector: prefer assignment or std::copy?

Violet Giraffe picture Violet Giraffe · Feb 20, 2013 · Viewed 84.1k times · Source

I have two vectors:

std::vector<int> v1, v2;

// Filling v1
...

And now I need to copy v1 to v2. Is there any reason to prefer

v2 = v1;

to

std::copy (v1.begin(), v1.end(), v2.begin());

(or vice versa)?

Answer

Grizzly picture Grizzly · Feb 20, 2013

Generally I would strongly prefer v2 = v1:

  1. It is shorter and makes the intend more clear
  2. std::copy won't work if v2 doesn't have the same length as v1 (it won't resize it, so it will retain some of the old elements best case (v2.size() > v1.size() and overwrite some random data used elsewhere in the program worst case
  3. If v1 is about to expire (and you use C++11) you can easily modify it to move the contents
  4. Performancewise assignment is unlikely to be slower then std::copy, since the implementers would probably use std::copy internally, if it gave a performance benefit.

In conclusion, std::copy is less expressive, might do the wrong thing and isn't even faster. So there isn't really any reason to use it here.