0

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?

jamman2000
  • 50
  • 6
  • `vec2.swap(vec1)` is efficient as much as `vec2 = std::move(vec1);`. `vec2 = vec1;` is less efficient. – 273K Jan 31 '22 at 07:27

2 Answers2

0

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.

littleadv
  • 20,100
  • 2
  • 36
  • 50
0

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436