Silicon Graphics, Inc.

count_if

Category: algorithms Component type: function

Prototype

template <class InputIterator, class Predicate, class Size>
void count_if(InputIterator first, InputIterator last, 
              Predicate pred,
              Size& n);

Description

Count finds the number of elements in [first, last) that satisfy the predicate pred. More precisely, it adds to n the number of iterators i in [first, last) such that pred(*i) is true. [1]

Definition

Defined in algo.h.

Requirements on types

Preconditions

Complexity

Linear. Exactly last - first applications of pred.

Example

int A[] = { 2, 0, 4, 6, 0, 3, 1, -7 };
const int N = sizeof(A) / sizeof(int);

int result = 0;
count_if(A, A + N, 
         compose1(bind2nd(equal_to<int>(), 0), bind2nd(modulus<int>(), 2)),
         result);
cout << "Number of even elements: " << result << endl;

Notes

[1] This is a rather clumsy interface: it would be more convenient if count_if simply returned the number of elements that satisfied pred. Unfortunately, this is impossible: the return type would have to be declared to be InputIterator's distance type, and there is no way to write such a declaration. As described in the iterator tag overview, there is actually a solution, using a traits class iterator_traits. This solution, however, relies on a C++ feature known as partial specialization. Partial specialization is part of the C++ standard, but no compilers currently (as of September 1996) support it. Once compilers that support partial specialization become available, future releases of the STL will use iterator traits.

See also

count, find, find_if
[Silicon Surf] [STL Home]
Copyright © 1996 Silicon Graphics, Inc. All Rights Reserved. TrademarkInformation