简体   繁体   中英

Move elements of vectors c++

How can I move certain elements of a vector into another vector while making the original smaller? I don't want to make a copy, i want to for example: in a vector of 5 elements, move the 1st element to another vector and now the original will have 4 elements.

First you want to use push_back to add the item to the second vector, then use erase to remove the item from the first vector. Both of these are members of the std::vector class.

An example:

std::vector<int> vec1, vec2;
//populate the first vector with some stuff
vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3); // so the vecotr is now { 1, 2, 3}
//Then move item 2 to the second vector
vec2.push_back(vec1[2]);
vec1.erase(2);

Edit: Though as others have pointed out, it looks like a vector may not be what you are looking for if this isn't the functionality you want. Have a look at the STL containers to see if there is something that is more fit for purpose.

std::vector<std::string> v1 = {"hello", "hello", "world", "c++", "hello", "stuff"};
std::vector<std::string> v2;

auto const pos = std::stable_partition(
    v1.begin(), v1.end(),
    [](std::string const& i) {
        // Condition in here. Return false to "remove" it.
         return "hello" != i;
    });
std::move(pos, v1.end(), std::back_inserter(v2));
// If you don't want to maintain current contents of v2, then
// this will be better than std::move:
// v2.assign(std::make_move_iterator(pos),
//           std::make_move_iterator(v1.end()));
v1.erase(pos, v1.end());

If you wanted to, you could write your own helper function to encapsulate this. See it working here .

You can use std::move to get a movable reference.

Not all types will allow you to move them. Also it's not guranteed that the instance you moved is in a correct state.

After you move you need to erase the location from the vector which will cause all the elements until the end of the vector to be copied/moved into the right position.

if you do not care about ordering you may use this:

std::swap(v1[index_of_item],v1.back());
v2.push_back(std::move(v1.back()));
v1.pop_back();

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