Although iterators make the algorithms container independent, most of the algorithms use one (or more) operation(s) on the element type. For example, step 2, uses the element type’s ==
operator to compare each element to the given value.
Other algorithms require that the element type have the <
operator. However, as we’ll see, most algorithms provide a way for us to supply our own operation to use in place of the default operator.
Exercise 10.1: The algorithm
header defines a function named count
that, like find
, takes a pair of iterators and a value. count
returns a count of how often that value appears. Read a sequence of int
s into a vector
and print the count
of how many elements have a given value.
Exercise 10.2: Repeat the previous program, but read values into a list
of string
s.
Key Concept: Algorithms Never Execute Container Operations
The generic algorithms do not themselves execute container operations. They operate solely in terms of iterators and iterator operations. The fact that the algorithms operate in terms of iterators and not container operations has a perhaps surprising but essential implication: Algorithms never change the size of the underlying container. Algorithms may change the values of the elements stored in the container, and they may move elements around within the container. They do not, however, ever add or remove elements directly.
As we’ll see in § 10.4.1 (p. 401), there is a special class of iterator, the inserters, that do more than traverse the sequence to which they are bound. When we assign to these iterators, they execute insert operations on the underlying container. When an algorithm operates on one of these iterators, the iterator may have the effect of adding elements to the container. The algorithm itself, however, never does so.