STL remove doesn't work as expected?

Viewed 7104
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, " ");
        std::vector< int > v(a, a + SIZE);
        std::vector< int >::iterator newLastElement;

        cout << "contents of the vector: ";
        std::copy(v.begin(), v.end(), output);

        newLastElement = std::remove(v.begin(), v.end(), 10);
        cout << "\ncontents of the vector after remove: ";
        //std::copy(v.begin(), newLastElement, output); 
                         //this gives the correct result : 2 35 5 26 67 2 5
        std::copy(v.begin(), v.end(), output);
          //this gives a 10 which was supposed to be removed : 2 35 5 26 67 2 5 2 5 10

        cout << endl;
        return 0;
}

There are three 10 in the array a.

why does the array v contains a 10 after we remove the all the 10s with remove function.

you can see the compiled output also here

4 Answers

C++20 introduces a new non-member function std::erase that simplifies this task for all standard library containers.

The solution suggested by multiple older answers here:

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

Can now be written as:

std::erase(v, 10);
Related