简体   繁体   中英

Performance of std::vector::swap vs std::vector::operator=

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?

swap will be more efficient since no copy is made. = will create a copy of vec1 in vec2 , keeping the original intact.

If you check the documentation, you'll see that swap is constant while = is linear.

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.

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