简体   繁体   中英

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

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

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.

The invocation of std::copy may try to access items beyond the end of the destination vector.

Use assignment.

It's not your job to micro-optimize: that's the library writer's responsibility, and ultimately the compiler's responsibility.

You can make your code arbitrarily fast if it doesn't have to be correct.

In the case of the copy , however, it's rather doubtful whether it even is faster, and it's certainly not correct for the general case.

If v2 isn't big enough you'll get a buffer overrun if you use copy as you have.

You can use a back insert iterator which will call push_back on v2 . However this could lead to multiple reallocations depending upon how big v1 is.

copy(v1.begin(), v1.end(), back_inserter(v2));

You're better off letting vector manage things correctly. The assignment operator does this, as does vector::assign :

v2.assign(v1.begin(), v1.end());

I have an inkling that the assignment operator is implemented in terms of vector::assign .

It's shorter.

std::copy is mainly meant for copying sections of containers. If you need to copy an entire container, you might as well use the copy constructor.

Assignment, by far. More generally, any time the size of the vector might change, or change the entire contents of the vector, you should prefer member functions. The only time std::copy would be appropriate is if you are only replacing a small range totally within the vector.

Assignement更清晰,内部使用std::copy (或unitizalized_copy _M_allocate_and_copy具体取决于大小和容量),因此性能相同。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM