SPrashad SPrashad - 10 days ago 5
C++ Question

How to move the first element of a vector to the end of another

I have two vectors of the same type, shown below:

std::vector<Task*> ToRun;
std::vector<Task*> Completed;


When a
Task
is finished, it needs to be automatically moved from the
ToRun
vector container into the
Completed
vector.

ToRun Vector contains
TaskOne TaskTwo TaskThree ... TaskN


Completed Vector contains
nothing


After the first loop through the
ToRun
vector, both vectors should look like below:

ToRun vector contains
TaskTwo TaskThree ... TaskN


Completed Vector contains
TaskOne


The second loop through the
ToRun
vector should look like below:

ToRun vector contains
TaskThree ... TaskN


Completed Vector contains
TaskOne TaskTwo


I have the below code but I'm receiving the following error:

Vector Moving Error

Code snippet:

for (auto iter = ToRun.begin(); iter != ToRun.end(); iter++)
{
(*iter)->dump(os);

Completed.push_back(std::move(ToRun.front()));
ToRun.erase(ToRun.begin());
}


I've tried looking at this and this SO answer however I'm having no luck. From what is happening, I think that the iterator points to null after I've moved the front element.

Should I attempt to move the Task from one container to another and then
remove
instead of erase?

Answer

Erasing while iterating is always messy. If you erase the current element, how can ++ work?

Instead try

while (!ToRun.empty()) // loop until empty
{
    ToRun.front()->dump(os);

    Completed.push_back(std::move(ToRun.front()));
    ToRun.erase(ToRun.begin());
}

or something similar

Comments