复制 std::vector:更喜欢赋值还是 std::copy?
我有两个向量:
std::vector<int> v1, v2;
// Filling v1
...
现在我需要将 v1
复制到 v2
.有什么理由更喜欢
And now I need to copy v1
to v2
. Is there any reason to prefer
v2 = v1;
到
std::copy (v1.begin(), v1.end(), v2.begin());
(反之亦然)?
推荐答案
一般来说我更喜欢 v2 = v1
:
- 它更短,使意图更清晰 如果
std::copy
将不起作用(它不会调整它的大小),所以它会在最好的情况下保留一些旧元素(v2.size() > v1.size()
并覆盖程序最坏情况下其他地方使用的一些随机数据- 如果
v1
即将过期(并且您使用 C++11),您可以轻松修改它以移动
内容 - 性能分配不太可能比
std::copy
慢,因为实施者可能会在内部使用std::copy
,如果它能带来性能优势.
v2
与 v1
的长度不同,- It is shorter and makes the intent more clear
std::copy
won't work ifv2
doesn't have the same length asv1
(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 tomove
the contents - Performancewise assignment is unlikely to be slower then
std::copy
, since the implementers would probably usestd::copy
internally, if it gave a performance benefit.
总而言之,std::copy
的表现力较差,可能会做错事,甚至更快.所以真的没有任何理由在这里使用它.
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.
相关文章