![]() |
![]() |
Category: algorithms | Component type: function |
template <class InputIterator, class Predicate, class Size> void count_if(InputIterator first, InputIterator last, Predicate pred, Size& n);
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;
[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.