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 と等しい要素を数えます 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 を返す単項述語。

p ( v ) は、 VT 型(const修飾されている可能性もある)のあらゆる引数 v に対して bool に変換可能でなければならず、 値カテゴリ に関わらず、 v を変更してはならない。したがって、 VT & のパラメータ型は許可されない 。また、 VT について、ムーブがコピーと等価でない限り、 VT も許可されない (C++11以降) 。 ​

型要件
-
InputIt LegacyInputIterator の要件を満たさなければならない。
-
ForwardIt LegacyForwardIterator の要件を満たさなければならない。
-
UnaryPred Predicate の要件を満たさなければならない。

戻り値

以下の条件を満たす it の数( 範囲 [ first , last ) 内のイテレータ):

1,2) * it == value true です。
3,4) p ( * it ) ! = false true です。

計算量

与えられた N std:: distance ( first, last ) として:

1,2) 厳密に N 回の比較を value に対して operator == を使用して実行します。
3,4) 厳密に N 回の述語 p の適用。

例外

ExecutionPolicy という名前のテンプレートパラメータを持つオーバーロードは、 以下のようにエラーを報告します:

  • アルゴリズムの一部として呼び出された関数の実行が例外をスローした場合、 ExecutionPolicy 標準ポリシー のいずれかであるとき、 std::terminate が呼び出されます。それ以外の ExecutionPolicy については、動作は実装定義です。
  • アルゴリズムがメモリの確保に失敗した場合、 std::bad_alloc がスローされます。

注記

範囲内の要素数について、 [ first , last ) に追加条件がない場合は、 std::distance を参照してください。

機能テスト マクロ 標準 機能
__cpp_lib_algorithm_default_value_type 202403 (C++26) リスト初期化 アルゴリズム用 ( 1,2 )

実装例

関連実装として count libstdc++ および 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;
}

#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 Applied to Behavior as published Correct behavior
LWG 283 C++98 T EqualityComparable であることが要求されていたが、
InputIt の値型が常に T ではない
要求を削除

関連項目

2つのイテレータ間の距離を返す
(関数テンプレート)
特定の条件を満たす要素の数を返す
(アルゴリズム関数オブジェクト)