erase() after performing remove_if()

前端 未结 2 1849
囚心锁ツ
囚心锁ツ 2020-12-20 12:50

I\'ve created a function to run through a vector of strings and remove any strings of length 3 or less. This is a lesson in using the STL Algorithm library.

I\'m ha

相关标签:
2条回答
  • 2020-12-20 13:03

    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
    
    0 讨论(0)
  • 2020-12-20 13:03

    You should be using the two parameter form of erase:

    myVector.erase(remove_if(myVector.begin(), myVector.end(), StringLengthTest),
                   myVector.end());
    
    0 讨论(0)
提交回复
热议问题