Erasing elements from a vector

后端 未结 5 811
萌比男神i
萌比男神i 2020-11-21 12:57

I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be presen

5条回答
  •  清歌不尽
    2020-11-21 13:43

    Use the remove/erase idiom:

    std::vector& vec = myNumbers; // use shorter name
    vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
    

    What happens is that remove compacts the elements that differ from the value to be removed (number_in) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes these elements (whose value is unspecified).

提交回复
热议问题