Silicon Graphics, Inc.

count

Category: algorithms Component type: function

Prototype

template <class InputIterator, class EqualityComparable, class Size>
void count(InputIterator first, InputIterator last, 
           const EqualityComparable& value,
           Size& n);

Description

Count finds the number of elements in [first, last) that are equal to value. More precisely, it adds to n the number of iterators i in [first, last) such that *i == value. [1]

Definition

Defined in algo.h.

Requirements on types

Preconditions

Complexity

Linear. Exactly last - first comparisons.

Example

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

int result = 0;
count(A, A + N, 0, result);
cout << "Number of zeros: " << result << endl;

Notes

[1] This is a rather clumsy interface: it would be more convenient if count simply returned the number of elements equal to value. 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_if, find, find_if
[Silicon Surf] [STL Home]
Copyright © 1996 Silicon Graphics, Inc. All Rights Reserved. TrademarkInformation