Given two vectors of equal length:
std::vector<Type> vec1;
std::vector<Type> vec2;
If the contents of vec2
need to be replaced with the contents of vec1
, is it more efficient to use
vec2.swap(vec1);
or
vec2 = vec1;
assuming that vec1
will remain in memory but its contents after the operation don't matter? Also, is there a more efficient method that I haven't considered?
The most expressive way, which is also optimally efficient, is:
vec2 = std::move(vec1);
In practice this will probably leave vec1
empty, but basically it just means you don't care about its content anymore, you want that moved to vec2
.
It's as efficient as swap, and much more efficient than copy assignment.
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.