Boost logo

Boost Users :

Subject: Re: [Boost-users] [range] count vs count_if
From: Bill Buklis (boostusr_at_[hidden])
Date: 2012-02-13 12:26:16

On 2/12/2012 7:03 AM, John M. Dlugosz wrote:
> On 2/10/2012 11:39 AM, Bill Buklis wrote:
>>>> What am I missing? How can count_if be properly expressed as count.
>>>> To me it seems like it
>>>> can't.
> I agree. "count returns the number of elements x in rng where x ==
> val is true."
> If you filter the original range using the predicate instead, you
> don't want to then compare them all against some constant. If you did
> so, you would need a special value such that every one of them
> compared true.
> You just want to count the number of items in the range you get after
> filtering. The obvious boost::size requires a bidirectional range,
> and is probably less efficient then we would want.
> Nathan mentioned boost::distance, which is hard to find in the
> documentation. But I see it listed on the synopsis under Forward
> Range functions. I guess it's missing from the page
> doc/range/concepts/forward_range.html
> In general, it is true that having two algorithms "do something with
> or to each element" and "same, but selecting elements via a predicate"
> can be generalized to using the first (only) with a range filter.
> But count and count_if are not such a pair. count also has a built-in
> predicate, but of the form el==value, rather than acting implicitly on
> all the elements.
> —John

Indeed, the documentation must be wrong. Hopefully it can be
appropriately fixed soon.

That is an excellent suggestion about using distance. I had not thought
of that, nor, come to think of it, did I even know that there was a
boost::distance function. But, it makes sense. On the other hand, I do
have to wonder if using "distance" for "count" would obfuscate the code.
In general, I think I would rather use count_if just for clarity. But,
at least the statement that the "_if functions aren't required", still
holds true even if it may not be rather obvious which one to use.


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at