Read-only range algorithms
In the preceding chapters, we built up an algorithm that we called distance
and another called count_if
. Both of these algorithms appear in the standard library.
std::count_if(a,b,p)
returns the number of elements between a
and b
that satisfy the predicate function p
--that is, the number of elements e
for which p(e)
is true
.
Notice that, whenever we say "between a
and b
", we're talking about the range that includes *a
but does not include *b
--what mathematicians call a "half-open range" and represented by the asymmetrical notation [a,b)
. Why should we not include *b
? Well, for one thing, if b
is the end()
of some vector, then it doesn't point to an element of that vector at all! So in general, dereferencing the end point of a range is a dangerous thing to do. For another thing, using half-open ranges conveniently allows us to represent empty ranges; for example, the range "from x
to x
" is an empty range consisting of zero data elements.
Half-open ranges are quite...