Rogue Wave banner
Previous fileTop of documentContentsIndexNext file

count, count_if


Algorithm

Summary

Count the number of elements in a container that satisfy a given condition.

Data Type and Member Function Indexes
(exclusive of constructors and destructors)

None

Synopsis

#include <algorithm>
template<class InputIterator, class T>
 typename iterator_traits<InputIterator>::difference_type
 count(InputIterator first, InputIterator last, 
       const T& value);
template <class InputIterator, class T, class Size>
 void count(InputIterator first, InputIterator last,
            const T& value, Size& n);
template<class InputIterator, class Predicate>
 typename iterator_traits<InputIterator>::difference_type
 count_if(InputIterator first, InputIterator last, 
          Predicate pred);
template <class InputIterator, class Predicate, class Size>
 void count_if(InputIterator first, InputIterator last,
               Predicate pred, Size& n);

Description

The count algorithm compares value to elements in the sequence defined by iterators first and last. The first version of count returns the number of matches. The second version 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 [first, last) 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 [first, last) for which the following condition holds:

pred(*i) == true.

Both count and count_if perform exactly last-first applications of the corresponding predicate.

Example

Program Output

Warnings

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

If your compiler does not support default template parameters, then you always need to supply the Allocator template argument. For instance, you have to write:

vector <int, allocator<int> >

instead of:

vector <int>

If your compiler does not support namespaces, then you do not need the using declaration for std.



Previous fileTop of documentContentsIndexNext file
©Copyright 1998, Rogue Wave Software, Inc.
Send mail to report errors or comment on the documentation.
OEM Release, June 1998