“move” two vectors together

前端 未结 2 1182
遥遥无期
遥遥无期 2020-12-23 18:29

If I have two vectors and want to combine them to one, I can do it the following way:

std::vector a(100); // just some random size here
std::vector&         


        
2条回答
  •  自闭症患者
    2020-12-23 19:01

    Depends on exactly what you want to move. When you move a vector, it is done by effectively swapping the internal array pointer. So you can make one vector point to the array previously owned by another vector.

    But that won't let you merge two vectors.

    The best you can do then is to move every individual member element, as shown in Kerrek's answer:

    std::move(b.begin(), b.end(), std::back_inserter(a));
    

    Again, this will iterate through the vector and move every element to the target vector.

提交回复
热议问题