Namespaces
Variants

std:: count, std:: count_if

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
(C++11) (C++11) (C++11)
count count_if

Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
헤더에 정의됨 <algorithm>
(1)
template < class InputIt, class T >

typename std:: iterator_traits < InputIt > :: difference_type

count ( InputIt first, InputIt last, const T & value ) ;
(C++20부터 constexpr)
(C++26까지)
template < class InputIt, class T = typename std:: iterator_traits

< InputIt > :: value_type >
constexpr typename std:: iterator_traits < InputIt > :: difference_type

count ( InputIt first, InputIt last, const T & value ) ;
(C++26부터)
(2)
template < class ExecutionPolicy, class ForwardIt, class T >

typename std:: iterator_traits < ForwardIt > :: difference_type
count ( ExecutionPolicy && policy,

ForwardIt first, ForwardIt last, const T & value ) ;
(C++17부터)
(C++26 이전까지)
template < class ExecutionPolicy,

class ForwardIt, class T = typename std:: iterator_traits
< ForwardIt > :: value_type >
typename std:: iterator_traits < ForwardIt > :: difference_type
count ( ExecutionPolicy && policy,

ForwardIt first, ForwardIt last, const T & value ) ;
(C++26부터)
template < class InputIt, class UnaryPred >

typename std:: iterator_traits < InputIt > :: difference_type

count_if ( InputIt first, InputIt last, UnaryPred p ) ;
(3) (C++20부터 constexpr)
template < class ExecutionPolicy, class ForwardIt, class UnaryPred >

typename std:: iterator_traits < ForwardIt > :: difference_type
count_if ( ExecutionPolicy && policy,

ForwardIt first, ForwardIt last, UnaryPred p ) ;
(4) (C++17부터)

지정된 기준을 만족하는 범위 [ first , last ) 내의 요소 개수를 반환합니다.

1) value 와 동일한 요소들의 개수를 셉니다 (using operator == ).
3) 술어 p true 를 반환하는 요소들의 개수를 셉니다.
2,4) (1,3) 와 동일하지만, policy 에 따라 실행됩니다.
다음 모든 조건이 만족될 때만 이 오버로드들이 오버로드 해결에 참여합니다:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true 입니다.

(C++20 이전)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true 입니다.

(C++20 이후)

목차

매개변수

first, last - 검사할 요소들의 범위 를 정의하는 반복자 쌍
value - 검색할 값
policy - 사용할 실행 정책
p - 필요한 요소에 대해 ​ true 를 반환하는 단항 predicate.

표현식 p ( v ) VT 타입의 (const 가능성 있는) 모든 인수 v 에 대해 bool 로 변환 가능해야 하며, 값 범주 와 관계없이 v 를 수정해서는 안 됩니다. 따라서 VT & 매개변수 타입은 허용되지 않으며 , VT 에 대해 이동이 복사와 동등하지 않는 한 VT 타입도 허용되지 않습니다 (C++11부터) . ​

타입 요구사항
-
InputIt LegacyInputIterator 요구사항을 충족해야 합니다.
-
ForwardIt LegacyForwardIterator 요구사항을 충족해야 합니다.
-
UnaryPred Predicate 요구사항을 충족해야 합니다.

반환값

다음 조건을 만족하는 범위 [ first , last ) 내의 반복자 it 의 개수:

1,2) * it == value true 입니다.
3,4) p ( * it ) ! = false true 입니다.

복잡도

주어진 N std:: distance ( first, last ) 인 경우:

1,2) 정확히 N 번의 비교를 value 와 수행하며, 이를 위해 operator == 를 사용합니다.
3,4) 정확히 N 번의 predicate p 적용.

예외

ExecutionPolicy 라는 템플릿 매개변수를 사용하는 오버로드는 다음과 같이 오류를 보고합니다:

  • 알고리즘의 일부로 호출된 함수 실행 중 예외가 발생하고 ExecutionPolicy 표준 정책 중 하나인 경우, std::terminate 가 호출됩니다. 다른 ExecutionPolicy 의 경우 동작은 구현에 따라 정의됩니다.
  • 알고리즘이 메모리 할당에 실패하는 경우, std::bad_alloc 이 throw됩니다.

참고 사항

범위 내 요소의 개수에 대해 [ first , last ) 와 같은 추가 기준 없이 확인하려면 std::distance 를 참조하십시오.

기능 테스트 매크로 표준 기능
__cpp_lib_algorithm_default_value_type 202403 (C++26) 목록 초기화 for algorithms ( 1,2 )

가능한 구현

다음 구현도 참조하십시오: count in libstdc++ and libc++ .

다음 구현들도 참조하십시오: count_if libstdc++ libc++ 에서의 구현.


count (1)
template<class InputIt, class T = typename std::iterator_traits<InputIt>::value_type>
typename std::iterator_traits<InputIt>::difference_type
    count(InputIt first, InputIt last, const T& value)
{
    typename std::iterator_traits<InputIt>::difference_type ret = 0;
    for (; first != last; ++first)
        if (*first == value)
            ++ret;
    return ret;
}
count_if (3)
template<class InputIt, class UnaryPred>
typename std::iterator_traits<InputIt>::difference_type
    count_if(InputIt first, InputIt last, UnaryPred p)
{
    typename std::iterator_traits<InputIt>::difference_type ret = 0;
    for (; first != last; ++first)
        if (p(*first))
            ++ret;
    return ret;
}
**번역 참고사항:** - HTML 태그와 속성은 번역하지 않음 - ` `, `
`, `` 태그 내부 텍스트는 번역하지 않음
- C++ 관련 용어는 번역하지 않음
- 원본 서식과 구조를 완전히 보존

예제

#include <algorithm>
#include <array>
#include <cassert>
#include <complex>
#include <iostream>
#include <iterator>
int main()
{
    constexpr std::array v{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';
    // 특정 대상 값과 일치하는 정수의 개수를 구합니다.
    for (const int target : {3, 4, 5})
    {
        const int num_items = std::count(v.cbegin(), v.cend(), target);
        std::cout << "number: " << target << ", count: " << num_items << '\n';
    }
    // 4로 나누어 떨어지는 요소들을 세기 위해 람다 표현식을 사용합니다.
    int count_div4 = std::count_if(v.begin(), v.end(), [](int i) { return i % 4 == 0; });
    std::cout << "numbers divisible by four: " << count_div4 << '\n';
    // O(N) 복잡도를 가진 `distance`의 단순화된 버전:
    auto distance = [](auto first, auto last)
    {
        return std::count_if(first, last, [](auto) { return true; });
    };
    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가 추론되어 리스트 초기화가 가능해집니다
        auto c = std::count(nums.cbegin(), nums.cend(), {4, 2});
    #else
        auto c = std::count(nums.cbegin(), nums.cend(), std::complex<double>{4, 2});
    #endif
    assert(c == 2);
}

출력:

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

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 283 C++98 T EqualityComparable 요구사항을 충족해야 했으나,
InputIt 의 값 타입이 항상 T 가 아님
해당 요구사항 제거

참고 항목

두 반복자 사이의 거리를 반환합니다
(함수 템플릿)
특정 조건을 만족하는 요소의 개수를 반환합니다
(알고리즘 함수 객체)