简体   繁体   中英

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?

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

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