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

c++, copy, stl

Solution

Generally I would strongly prefer `v2 = v1`:

- It is shorter and makes the intent more clear

- `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

- If `v1` is about to expire (and you use C++11) you can easily modify it to `move` the contents

- 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.

Problem

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)?

Original source