STL remove doesn't work as expected?

前端 未结 3 1624
夕颜
夕颜 2020-11-27 20:21
int main()
{

        const int SIZE = 10;
        int a[SIZE] = {10, 2, 35, 5, 10, 26, 67, 2, 5, 10};
        std::ostream_iterator< int > output(cout, \" \")         


        
3条回答
  •  攒了一身酷
    2020-11-27 21:06

    The reason is that STL algorithms do not modify the size of the sequence. remove, instead of actually erasing items, moves them and returns an iterator to the "new" end. That iterator can then be passed to the erase member function of your container to actually perform the removal:

    v.erase(std::remove(v.begin(), v.end(), 10), v.end());
    

    By the way, this is known as the "erase-remove idiom".

    EDIT: I was incorrect. See comments, and Nawaz's answer.

提交回复
热议问题