Syntax:
#include <algorithm> typename iterator_traits<input_iterator>::difference_type count_if( input_iterator start, input_iterator end, UnaryPred p );
The count_if
function returns the number of elements between start
and end
for which the predicate p
returns true.
For example, the following code uses count_if
with a predicate that returns
true for the integer 3 to count the number of items in an array that are equal
to 3:
int nums[] = { 0, 1, 2, 3, 4, 5, 9, 3, 13 }; int start = 0; int end = 9; int target_value = 3; int num_items = count_if( nums+start, nums+end, bind2nd(equal_to<int>(), target_value) ); cout << "nums[] contains " << num_items << " items matching " << target_value << endl;
When run, the above code displays the following output:
nums[] contains 2 items matching 3
Alternatively, the same result can be achieved with the boost::bind
:
int num_items = count_if( nums+start, nums+end, boost::bind(equal_to<int>(), target_value, _1) );
count_if
can also be used on containers such as vectors:
int num_items = count_if( nums.begin(), nums.end(), boost::bind(equal_to<int>(), target_value, _1) );
Related Topics: count