# The Remove_if() Algorithm If you are familiar with the remove_if() algorithm, you’re used to applying remove_if() followed by erase(). For example, suppose you’re given a predicate to determine whether a number is even:

``vector::iterator p = remove_if(coll.begin(), coll.end(), even);coll.erase(p, coll.end());``

This code takes a vector with the contents:

``1 2 3 4 5 6``

This results in the vector containing:

``1 3 5``

It’s easy to fall into the trap of thinking that the remove_if() algorithm moves the items that you wish to be deleted to the end of the vector prior to erasure. A number of Web pages also give this impression. Don’t believe them!

For example, if you wished to sum the even numbers before erasing them, you might be tempted to try:

``vector::iterator p = remove_if(coll.begin(), coll.end(), even);int sum = accumulate(p, coll.end(), 0);coll.erase(p, coll.end());``

When this returns a sum of 15, you should realise that something has gone wrong!

In fact, remove_if() does not move the items to be deleted anywhere. Instead, the items to be kept are simply moved towards the beginning of the vector, overwriting the original contents and resulting in the following contents before erase is called:

``1 3 5 4 5 6``

If you really want to perform some processing on the elements to be deleted, before the final call to erase, use partition() or stable_partition() instead. These algorithms arrange those items that match the predicate at the beginning of the container and those that don’t at the end. So, to sum those even numbers before erasing them, try the following:

``vector::iterator p = partition(coll.begin(), coll.end(), even);int sum = accumulate(coll.begin(), p, 0);coll.erase(coll.begin(), p);``

This will give the correct sum (12) and leave the items in the vector:

``3 5 1``

If you want to keep the original ordering of these elements, use stable_partition() instead.

Share the Post:

Recent Articles: