Search code examples
c++stdvectorstl-algorithm

Erasing particular elements in a vector with algorithm


I am trying to figure out how remove_if and vector<T>::erase works. I have the code below (trying to remove odd elements):

v2.clear();
v2 = { 10, 20, 21, 30, 31, 33, 44, 66, 67 }; //vector<int>
cout << "v2 is now: " << endl;
printCollection(v2);    
cout << "Trying to remove odds from v2: " << endl;
auto what = remove_if(begin(v2), end(v2), [](int elem) {return elem % 2 != 0;});
v2.erase(begin(v2), what);
printCollection(v2);

and here is the output:

v2 is now:
10 20 21 30 31 33 44 66 67

Trying to remove odds from v2:
33 44 66 67

What is going on?


Solution

  • The behaviour of your code is unspecified. std::remove_if moves all non-removed elements to the front of the container and returns the new logical end iterator. All elements between this new end (what in your code) and .end() have unspecified values.

    You should erase from what to .end() instead:

    v2.erase(what, end(v2));
    

    demo