beautypg.com

Removal algorithms, Remove unwanted elements, Chapter 13 – HP Integrity NonStop H-Series User Manual

Page 165: Remove unwanted, Elements

background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Removal Algorithms

What is a Name?

The following two algorithms can be somewhat confusing the first time they are encountered.
Both claim to remove certain values from a sequence. But, in fact, neither one reduces the size
of the sequence. Both operate by moving the values that are to be retained to the front of the
sequence, and returning an iterator that describes where this sequence ends. Elements after this
iterator are simply the original sequence values, left unchanged. This is necessary because the
generic algorithm has no knowledge of the container it is working on. It only has a generic
iterator. This is part of the price we pay for generic algorithms. In most cases the user will want
to use this iterator result as an argument to the erase() member function for the container,
removing the values from the iterator to the end of the sequence.

Let us illustrate this with a simple example. Suppose we want to remove the even numbers from
the sequence 1 2 3 4 5 6 7 8 9 10, something we could do with the remove_if() algorithm. The
algorithm remove_if() would leave us with the following sequence:

1 3 5 7 9 | 6 7 8 9 10

The vertical bar here represents the position of the iterator returned by the remove_if()
algorithm. Notice that the five elements before the bar represent the result we want, while the
five values after the bar are simply the original contents of those locations. Using this iterator
value along with the end-of-sequence iterator as arguments to erase(), we can eliminate the
unwanted values, and obtained the desired result.

Both the algorithms described here have an alternative copy version. The copy version of the
algorithms leaves the original unchanged, and places the preserved elements into an output
sequence.

Remove Unwanted Elements

Obtaining the Source

The algorithm remove() eliminates unwanted values from a sequence. As with the find()
algorithm, these can either be values that match a specific constant, or values that satisfy a
given predicate. The declaration of the argument types is as follows:

This manual is related to the following products: