Namespaces
Variants

std::ranges:: count, std::ranges:: 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
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
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더 파일에 정의됨 <algorithm>
호출 시그니처
(1)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class T, class Proj = std:: identity >
requires std:: indirect_binary_predicate
< ranges:: equal_to , std :: projected < I, Proj > , const T * >
constexpr std:: iter_difference_t < I >

count ( I first, S last, const T & value, Proj proj = { } ) ;
(C++20부터)
(C++26까지)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
class T = std :: projected_value_t < I, Proj > >
requires std:: indirect_binary_predicate
< ranges:: equal_to , std :: projected < I, Proj > , const T * >
constexpr std:: iter_difference_t < I >

count ( I first, S last, const T & value, Proj proj = { } ) ;
(C++26부터)
(2)
template < ranges:: input_range R, class T, class Proj = std:: identity >

requires std:: indirect_binary_predicate
< ranges:: equal_to ,
std :: projected < ranges:: iterator_t < R > , Proj > , const T * >
constexpr ranges:: range_difference_t < R >

count ( R && r, const T & value, Proj proj = { } ) ;
(C++20부터)
(C++26까지)
template < ranges:: input_range R, class Proj = std:: identity ,

class T = std :: projected_value_t < ranges:: iterator_t < R > , Proj > >
requires std:: indirect_binary_predicate
< ranges:: equal_to ,
std :: projected < ranges:: iterator_t < R > , Proj > , const T * >
constexpr ranges:: range_difference_t < R >

count ( R && r, const T & value, Proj proj = { } ) ;
(C++26부터)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
std:: indirect_unary_predicate < std :: projected < I, Proj >> Pred >
constexpr std:: iter_difference_t < I >

count_if ( I first, S last, Pred pred, Proj proj = { } ) ;
(3) (C++20 이후)
template < ranges:: input_range R, class Proj = std:: identity ,

std:: indirect_unary_predicate <
std :: projected < ranges:: iterator_t < R > , Proj >> Pred >
constexpr ranges:: range_difference_t < R >

count_if ( R && r, Pred pred, Proj proj = { } ) ;
(4) (C++20 이후)

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

1) value 와 동일한 요소들의 개수를 셉니다.
3) 술어 p true 를 반환하는 요소들의 개수를 셉니다.
2,4) (1,3) 와 동일하지만, r 를 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first, last - 검사할 요소들의 범위 를 정의하는 반복자-감시자 쌍
r - 검사할 요소들의 범위
value - 검색할 값
pred - 투영된 요소들에 적용할 predicate
proj - 요소들에 적용할 projection

반환값

조건을 만족하는 요소의 개수.

복잡도

정확히 last - first 번의 비교와 projection.

참고 사항

범위 내 요소의 개수에 대한 추가 기준 없이 확인하려면 std::ranges::distance 를 참조하십시오.

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

가능한 구현

count (1)
struct count_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity, class T = std::projected_value_t<I, Proj>>
    requires std::indirect_binary_predicate<ranges::equal_to,
                                            std::projected<I, Proj>, const T*>
    constexpr std::iter_difference_t<I>
        operator()(I first, S last, const T& value, Proj proj = {}) const
    {
        std::iter_difference_t<I> counter = 0;
        for (; first != last; ++first)
            if (std::invoke(proj, *first) == value)
                ++counter;
        return counter;
    }
    template<ranges::input_range R, class Proj = std::identity
             class T = std::projected_value_t<ranges::iterator_t<R>, Proj>>
    requires std::indirect_binary_predicate<ranges::equal_to,
                                            std::projected<ranges::iterator_t<R>, Proj>,
                                            const T*>
    constexpr ranges::range_difference_t<R>
        operator()(R&& r, const T& value, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), value, std::ref(proj));
    }
};
inline constexpr count_fn count;
count_if (3)
struct count_if_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity,
             std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    constexpr std::iter_difference_t<I>
        operator()(I first, S last, Pred pred, Proj proj = {}) const
    {
        std::iter_difference_t<I> counter = 0;
        for (; first != last; ++first)
            if (std::invoke(pred, std::invoke(proj, *first)))
                ++counter;
        return counter;
    }
    template<ranges::input_range R, class Proj = std::identity,
             std::indirect_unary_predicate<
                 std::projected<ranges::iterator_t<R>, Proj>> Pred>
    constexpr ranges::range_difference_t<R>
        operator()(R&& r, Pred pred, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r),
                       std::ref(pred), std::ref(proj));
    }
};
inline constexpr count_if_fn count_if;

예제

#include <algorithm>
#include <cassert>
#include <complex>
#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v{1, 2, 3, 4, 4, 3, 7, 8, 9, 10};
    namespace ranges = std::ranges;
    // std::vector 내에서 대상 값과 일치하는 정수의 개수를 구합니다.
    int target1 = 3;
    int target2 = 5;
    int num_items1 = ranges::count(v.begin(), v.end(), target1);
    int num_items2 = ranges::count(v, target2);
    std::cout << "number: " << target1 << " count: " << num_items1 << '\n';
    std::cout << "number: " << target2 << " count: " << num_items2 << '\n';
    // 3으로 나누어 떨어지는 요소를 세기 위해 람다 표현식을 사용합니다.
    int num_items3 = ranges::count_if(v.begin(), v.end(), [](int i){ return i % 3 == 0; });
    std::cout << "number divisible by three: " << num_items3 << '\n';
    // 11으로 나누어 떨어지는 요소를 세기 위해 람다 표현식을 사용합니다.
    int num_items11 = ranges::count_if(v, [](int i){ return i % 11 == 0; });
    std::cout << "number divisible by eleven: " << num_items11 << '\n';
    std::vector<std::complex<double>> nums{{4, 2}, {1, 3}, {4, 2}};
    #ifdef __cpp_lib_algorithm_default_value_type
        auto c = ranges::count(nums, {4, 2});
    #else
        auto c = ranges::count(nums, std::complex<double>{4, 2});
    #endif
    assert(c == 2);
}

출력:

number: 3 count: 2
number: 5 count: 0
number divisible by three: 3
number divisible by eleven: 0

참고 항목

반복자와 센티넬 사이의 거리 또는 범위의 시작과 끝 사이의 거리를 반환합니다
(알고리즘 함수 객체)
반복자와 개수로부터 하위 범위를 생성합니다
(커스터마이제이션 포인트 객체)
조건자를 만족하는 range 요소들로 구성된 view
(클래스 템플릿) (범위 어댑터 객체)
특정 조건을 만족하는 요소의 개수를 반환합니다
(함수 템플릿)