vendredi 3 mars 2017

Moving objects from one vector to another using erase-remove paradigm

This question clearly articulates how to move contents from one std::vector to another. In short, there is a std::move call required to physically move the memory, while there is also a std::erase call necessary to resize the original vector to account for the removes elements.

Is there a problem doing this using the erase-remove paradigm as one uses to delete from a vector while iterating over it (like here).

For example, something like this:

// Vector with values [0, 1, ..., 19]
std::vector<int> myOldVec;
for (int i = 0; i < 20; i++) { myOldVec.push_back(i); }

// New vector to move into
std::vector<int> myNewVec;

// Move from myOldVec to myNewVec if value is less than 5
myOldVec.erase(
    std::remove_if(
        myOldVec.begin(),
        myOldVec.end(),
        [=](const int x)
        {
            myNewVec.push_back(x);
            return x < 5; 
        }
    ),
    myOldVec.end()
);

The intended output would be

myOldVec --> [5, 6, ..., 19]
myNewVec --> [0, 1, 2, 3, 4]

When I run this code it works in my tester. However, when dealing with objects instead of ints I worry that I'm not actually moving anything, but rather just referencing; for example, when doing the above with std::vector<MyObj> instead (with the appropriate lambda test).

Is this really performing a move, or am I right to be concerned that I'm just sharing a reference?

Aucun commentaire:

Enregistrer un commentaire