count |
Count items in a range that match a value.
Count the number of elements in
the range [ first , last
) that match value using operator==
and add this count to n . Note that n
is not automatically initialized to zero prior to the counting procedure.
#include <algorithm>
template< class InputIterator, class T, class Size >
void count
(
InputIterator first,
InputIterator last,
const T& value,
Size& n
);
Time complexity is linear, as (
last - first )
comparisons are performed. Space complexity is constant.
#include <iostream>
#include <algorithm>
int numbers[ 10 ] = { 1, 2, 4, 1, 2, 4, 1, 2, 4, 1 };
void
main()
{
int result = 0;
count( numbers, numbers + 10, 1, result );
cout << "Found " << result << " 1's.\n";
}
Found 4 1's.
#include <iostream>
#include <algorithm>
#include <vector>
void
main()
{
vector< int > numbers( 100 );
for ( int i = 0; i < 100; ++i )
numbers[ i ] = i % 3;
int elements = 0;
count( numbers.begin(), numbers.end(), 2, elements );
cout << "Found " << elements << " 2's.\n";
}
Found 33 2's.
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.