将元素从 std: : Vector 移动到另一个元素

如何将一些元素从第一个向量移动到第二个向量,并且元素将从第一个向量中移除?
如果我使用的是 std::move,那么第一个向量中没有移除的元素。
这是我写的代码:

   move(xSpaces1.begin() + 7, xSpaces1.end(), back_inserter(xSpaces2));
112332 次浏览

You can't move elements from one vector to another the way you are thinking about; you will always have to erase the element positions from the first vector.

If you want to change all the elements from the first vector into the second and vice versa you can use swap.

If you want to move the same amount of elements between two vectors, you can use swap_ranges

The std::move lets you move the objects, as opposed to copying them, allowing for a potentially faster execution speed. The savings may be even greater when you move a range of values. However, when you do move a range from a container, the container still holds the places that were once occupied by these values.

You need to resize the container manually to remove these placeholders if you want to get rid of them (you don't have to, in case you would prefer reusing these container spots for other elements). One way to do it is to call vector::erase on the same range that you moved out of the container.

std::move and std::copy operate on elements, not containers. You have to mutate the container separately. For example, to move the first 17 elements of v1 into a new vector v2:

std::vector<Foo> v1, v2;


// populate v1 with at least 17 elements...


auto it = std::next(v1.begin(), 17);


std::move(v1.begin(), it, std::back_inserter(v2));  // ##


v1.erase(v1.begin(), it);

After line ##, the first 17 elements of v1 are still there, but they've been "moved-from", so they're in an indeterminate state.

Resurrecting an old thread, but I am surprised that nobody mentioned std::make_move_iterator combined with insert. It has the important performance benefit of preallocating space in the target vector:

v2.insert(v2.end(), std::make_move_iterator(v1.begin() + 7),
std::make_move_iterator(v1.end()));

As others have pointed out, first vector v1 is now in indeterminate state, so use erase to clear the mess:

v1.erase(v1.begin() + 7, v1.end());