count_if [C++ Reference]
Keywords: stl,algorithm,count_if
Date: 2009-10-09T00:57:14-0700

[[count_if]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- fr
- it
- jp
- pl
- ru
- tr

## count_if

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

Related Topics: count

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •