erase() after performing remove_if()

你说的曾经没有我的故事 提交于 2019-11-28 13:20:20

It is easiest to understand this if you seperate the statements:

auto iter(remove_if(myVector.begin(), myVector.end(), StringLengthTest));
myVector.erase(iter);

These 2 lines do the same as your single line. And it should be clear now what the "bug" is. remove_if, works first. It iterates over the whole vector and moves all "selected" entries "to the end" (better said: it moves the non selected entries to the front). After it has run it returns an iterator to the "last" position of the left over entries, something like:

this
test
vector
test <- iterator points here
vector

Then you run erase with a single iterator. That means you erase a single element pointed at - so you erase the "test" element. - What is left over is what you are seeing.

To fix it simply erase from the vector returned by remove_if to the end().:

myVector.erase(remove_if(myVector.begin(), myVector.end(), StringLengthTest), myVector.end()); //erase anything in vector with length <= 3

You should be using the two parameter form of erase:

myVector.erase(remove_if(myVector.begin(), myVector.end(), StringLengthTest),
               myVector.end());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!