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.