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)?
The standard algorithm for copying is std::copy . We can use it for copying elements from the source vector to the destination vector.
Vector has an inbuilt function too to copy contents from other content. It's named assign() function. It's again a deep copy method.
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.
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.
Generally I would strongly prefer v2 = v1
:
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 casev1
is about to expire (and you use C++11) you can easily modify it to move
the contentsstd::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With