Why do you need to erase the entry in the list? Also your implementation seems to be missing one of your ones.
1 2 3 4 5
for(auto it = mylist.begin(); it != mylist.end(); it++) {
if(*it == 1) {
myvec.push_back(*it);
}
}
Also if you are are always going to push the same number into your vector maybe you just want to count the number of times this number exists in your list then construct your list with correct number of elements and the default value:
// After counting the number of ones. std::vector<int>myvec(NumberOfOnes,1);
But this is a very simplified version of my code. The original is very complexe. I have to erase all elements of 1 from the list, one by one. And push_back the vector of elements of 1, one by one.
Then I don't understand the problem. You say you must push_back the vector, and remove them from the list one by one. That's basically what you're doing. You do seem to be missing one element, I count 4 ones but the code you provided only pushes 3 to the vector.
The only speed up I can see would be to construct your vector with the same size as your list. Then you could use array access instead of the expensive push_back(). If you keep a count of the number of items deleted you can then resize the vector after the loop.