Erase all even numbers from vector using find

This question already has an answer here:

  • Iterator invalidation rules 4 answers

  • When using the erase(it); function the iterator changes so you need to set the iterator again to the new one returned by the erase function.

    In your code, you are checking for the end if(q == myVec.end()) and then using erase this will throw an error as.end() does not point to data, and to be able to erase an item from the vector the iterator needs to be valid. So by changing if(q == myVec.end()) to if(q == (myVec.end()-1)) it will allow you to delete the last element in case of been a pair.


    std::vector::erase invalidates all iterators to and after the point of erasure. You can't continue using that iterator, not to increment it, use it to access the vector, or even compare it to end() .

    The correct algorithm to use is std:remove_if . Unlike the name implies, it will only move all even items of the vector "to the back", without invalidating any iterators. It will return an iterator to the start of this sub-range, which you can then just feed to the appropriate erase overload (the one that accepts a pair of iterators).

    This has been used so much in code that it's even named "the erase-remove idiom".

    链接地址: http://www.djcxy.com/p/73344.html

    上一篇: 为什么相同的代码在Visual Studio和Dev中以不同的方式运行

    下一篇: 使用find从矢量中清除所有偶数