Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

copy

stl

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

like image 445
Violet Giraffe Avatar asked Feb 20 '13 10:02

Violet Giraffe


People also ask

Does std::vector copy?

The standard algorithm for copying is std::copy . We can use it for copying elements from the source vector to the destination vector.

Is vector assignment deep copy?

Vector has an inbuilt function too to copy contents from other content. It's named assign() function. It's again a deep copy method.

What is the time complexity of copying a vector?

Complexity :- O(n) as copy() takes linear time to traverse elements. But begin(),end() and back_inserter() takes constant time. This function takes 2 arguments, first iterator to old vector and last iterator to old vector. It then assigns values of old vector to new vector.

Should I use std for vector?

As a rule of thumb, you should use: a std::array if the size in fixed at compile time. a std::vector is the size is not fixed at compile time. a pointer on the address of their first element is you need low level access.


1 Answers

Generally I would strongly prefer v2 = v1:

  1. It is shorter and makes the intent 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.

like image 120
Grizzly Avatar answered Oct 26 '22 22:10

Grizzly