Boost logo

Boost Users :

Subject: Re: [Boost-users] [range] count vs count_if
From: John M. Dlugosz (mpbecey7gu_at_[hidden])
Date: 2012-02-12 08:03:34


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


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net