Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library Reference Guide

count(), count_if()

Library:  Algorithms


Function

Local Index

No Entries

Summary

Algorithm that counts the number of elements in a range that satisfy a given condition

Synopsis

#include <algorithm>

namespace std {
  template<class InputIterator, class T>
  typename iterator_traits<InputIterator>::difference_type
  count(InputIterator start, InputIterator finish, 
        const T& value);
  
  template <class InputIterator, class T, class Size>
  void count(InputIterator start, InputIterator finish,
             const T& value, Size& n);
  
  template<class InputIterator, class Predicate>
  typename iterator_traits<InputIterator>::difference_type
  count_if(InputIterator start, InputIterator finish, 
           Predicate pred);
  
  template <class InputIterator, class Predicate, class Size>
  void count_if(InputIterator start, InputIterator finish,
                Predicate pred, Size& n);
}

Description


NOTE -- The second versions of the count() and count_if() functions are not part of the C++ Standard, but are included here as extensions for compatibility purposes. See Appendix B for a complete list of extensions of this implementation.

The count() algorithm compares value to elements in the sequence defined by iterators start and finish. The first version of count() returns the number of matches. The second version, which is provided for backwards compatibility or as an alternative to the first in case the template iterator_traits isn't provided, increments a counting value n each time it finds a match. In other words, count() returns (or adds to n) the number of iterators i in the range [start, finish) for which the following condition holds:

*i == value

Type T must be EqualityComparable.

Complexity

The count_if() algorithm lets you specify a predicate, and returns the number of times an element in the sequence satisfies the predicate (or increments n that number of times). That is, count_if() returns (or adds to n) the number of iterators i in the range [start, finish) for which the following condition holds:

pred(*i) == true.

Both count() and count_if() perform exactly finish - start applications of the corresponding predicate.

Example

Warnings

If your compiler does not support partial specialization, the first version of both count() and count_if(), the version that returns the count, is not available.

Standards Conformance

ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 25.1.6



Previous fileTop of DocumentContentsIndex pageNext file