std::count, std::count_if

From Cppreference

Jump to: navigation, search
Defined in header <algorithm>

template< class InputIterator, class T >

typename iterator_traits<InputIterator>::difference_type

    count( InputIterator first, InputIterator last, const T &value );
(1)
template< class InputIterator, class UnaryPredicate >

typename iterator_traits<InputIterator>::difference_type

    count_if( InputIterator first, InputIterator last, UnaryPredicate p );
(2)

Returns the number of elements in the range [first, last) satisfying specific criteria. The first version counts the elements that are equal to value, the second version counts elements for which predicate p returns true.

Contents

Parameters

first, last - the range of elements to examine
value - the value to search for
p - unary predicate which returns ​true for the required elements.

The signature of the predicate function should be equivalent to the following:

bool pred(const Type &a);

The signature does not need to have const &, but the function must not modify the objects passed to it.
The type ​Type​ must be such that an object of type ​InputIterator​ can be dereferenced and then implicitly converted to ​Type​. ​

Return value

number of elements satisfying the condition.

Complexity

linear in the distance between first and last

Equivalent function

template<class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type
    count_if(InputIterator first, InputIterator last, UnaryPredicate p)
{
    typename iterator_traits<InputIterator>::difference_type ret = 0;
    for (; first != last; ++first) {
        if (p(*first)) {
            ret++;
        }
    }
    return ret;
}

Example

The following code uses count to determine how many integers in a vector match a target value:

#include <algorithm>
#include <iostream>
#include <vector>
 
int main()
{
    int data[] = { 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }
    std::vector<int> v(data, data+10);
 
    int target1 = 3;
    int target2 = 5;
    int num_items1 = std::count(v.begin(), v.end(), target1);
    int num_items2 = std::count(v.begin(), v.end(), target2);
 
    std::cout << "number: " << target1 << " count: " << num_items1 << std::endl;
    std::cout << "number: " << target2 << " count: " << num_items2 << std::endl;
 
    return 0;
}

Output:

​number: 3 count: 2
number: 5 count: 0​
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
In other languages