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
Actually
std::removedoesn’t remove the item from the container. Quoted from hereThat is,
std::removeworks with a pair of iterators only and does not know anything about the container which actually contains the items. In fact, it’s not possible forstd::removeto know the underlying container, because there is no way it can go from a pair of iterators to discover about the container to which the iterators belong. Sostd::removedoesn’t really remove the items, simply because it cannot. The only way to actually remove an item from a container is to invoke a member function on that container.So if you want to remove the items, then use Erase-Remove Idiom:
The erase-remove idiom is so common and useful is that
std::listhas added another member function calledlist::removewhich produces the same effect as that of theerase-removeidiom.That means, you don’t need to use
erase-removeidiom when you work withstd::list. You can directly call its member functionlist::remove.