std::count, std::count_if - cppreference.com

From cppreference.com

Defined in header

<algorithm>

template<classInputIt,classT>typenamestd::iterator_traits<InputIt>::difference_typecount(InputItfirst,InputItlast,constT&value); (1)(constexpr since C++20)
(until C++26)template<classInputIt,classT=typenamestd::iterator_traits<InputIt>::value_type>constexprtypenamestd::iterator_traits<InputIt>::difference_typecount(InputItfirst,InputItlast,constT&value);(since C++26)template<classInputIt,classUnaryPred>typenamestd::iterator_traits<InputIt>::difference_typecount_if(InputItfirst,InputItlast,UnaryPredp); (2)(constexpr since C++20)template<classExecutionPolicy,classForwardIt,classT>typenamestd::iterator_traits<ForwardIt>::difference_typecount(ExecutionPolicy&&policy,ForwardItfirst,ForwardItlast,constT&value); (3)(since C++17)
(until C++26)template<classExecutionPolicy,classForwardIt,classT=typenamestd::iterator_traits<ForwardIt>::value_type>typenamestd::iterator_traits<ForwardIt>::difference_typecount(ExecutionPolicy&&policy,ForwardItfirst,ForwardItlast,constT&value);(since C++26)template<classExecutionPolicy,classForwardIt,classUnaryPred>typenamestd::iterator_traits<ForwardIt>::difference_typecount_if(ExecutionPolicy&&policy,ForwardItfirst,ForwardItlast,UnaryPredp); (4) (since C++17)Returns the number of elements in the source range [first, last) satisfying specific criteria.

1) Counts the elements that are equal to value (using operator==).

2) Counts elements for which predicate p returns true.

3,4) Same as (1,2), but executed according to policy.

These overloads participate in overload resolution only if the value of the following expression is true:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(until C++20)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(since C++20)Parameters

first, last - the pair of iterators defining the source

range

value - the value to search for p - unary predicate which returns ​true for the required elements. The expression p(v) must be convertible to bool for every argument v of type (possibly const) VT, where VT is the value type of InputIt, regardless of

value category

, and must not modify v. Thus, a parameter type of VT&is not allowed, nor is VT unless for VT a move is equivalent to a copy(since C++11). ​

policy - the

execution policy

to use Type requirements -InputIt must meet the requirements of

LegacyInputIterator

. -ForwardIt must meet the requirements of

LegacyForwardIterator

. -UnaryPred must meet the requirements of

Predicate

. Return value

The number of iterators iter in the source range satisfying the following condition:

1,3)*iter==value is true.

2,4)p(*iter)!=false is true.

Complexity

Given N as std::distance(first,last):

1) Exactly N comparisons with value using operator==.

2) Exactly N applications of p.

3)𝓞(N) comparisons with value using operator==.

4)𝓞(N) applications of p.

Exceptions

3,4) During the execution process:

If the temporary memory resources required for parallelization are not available,

std::bad_alloc

is thrown.

If an uncaught exception is thrown while accessing objects via an algorithm argument, the behavior is determined by the execution policy (for

standard policies

,

std::terminate

is invoked).

Notes

For the number of elements in a range without any additional criteria, see

std::distance

.

Feature-test

macroValueStdFeature

__cpp_lib_algorithm_default_value_type

202403

(C++26)

List-initialization

for algorithms (

1,3

)Possible implementation

See also the implementations of count in

libstdc++

and

libc++

.

See also the implementations of count_if in

libstdc++

and

libc++

.

count

template<classInputIt,classT=typenamestd::iterator_traits<InputIt>::value_type>typenamestd::iterator_traits<InputIt>::difference_typecount(InputItfirst,InputItlast,constT&value){typenamestd::iterator_traits<InputIt>::difference_typeret=0;for(;first!=last;++first)if(*first==value)++ret;returnret;}

count_if

template<classInputIt,classUnaryPred>typenamestd::iterator_traits<InputIt>::difference_typecount_if(InputItfirst,InputItlast,UnaryPredp){typenamestd::iterator_traits<InputIt>::difference_typeret=0;for(;first!=last;++first)if(p(*first))++ret;returnret;}Example

Run this code

#include<algorithm>#include<array>#include<cassert>#include<complex>#include<iostream>#include<iterator>intmain(){constexprstd::arrayv{1,2,3,4,4,3,7,8,9,10};std::cout<<"v: ";std::copy(v.cbegin(),v.cend(),std::ostream_iterator<int>(std::cout," "));std::cout<<'\n';// Determine how many integers match a target value.for(constinttarget:{3,4,5}){constintnum_items=std::count(v.cbegin(),v.cend(),target);std::cout<<"number: "<<target<<", count: "<<num_items<<'\n';}// Use a lambda expression to count elements divisible by 4.intcount_div4=std::count_if(v.begin(),v.end(),[](inti){returni%4==0;});std::cout<<"numbers divisible by four: "<<count_div4<<'\n';// A simplified version of “distance” with O(N) complexity:autodistance=[](autofirst,autolast){returnstd::count_if(first,last,[](auto){returntrue;});};static_assert(distance(v.begin(),v.end())==10);std::array<std::complex<double>,3>nums{{{4,2},{1,3},{4,2}}};#ifdef __cpp_lib_algorithm_default_value_type// T gets deduced making list-initialization possibleautoc=std::count(nums.cbegin(),nums.cend(),{4,2});#elseautoc=std::count(nums.cbegin(),nums.cend(),std::complex<double>{4,2});#endifassert(c==2);}Output:

v: 1 2 3 4 4 3 7 8 9 10 number: 3, count: 2 number: 4, count: 2 number: 5, count: 0 numbers divisible by four: 3 Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior

LWG 283

C++98 T was required to be

EqualityComparable

, but
the value type of InputIt is not always Tremoved the requirement See also