名前空間
変種
操作

std::count, std::count_if

From cppreference.com
< cpp‎ | algorithm
 
 
アルゴリズムライブラリ
制約付きアルゴリズムとRangeアルゴリズム (C++20)
制約付きアルゴリズム、例: ranges::copy, ranges::sort, ...
実行ポリシー (C++17)
シーケンスを変更しない操作
一括操作
(C++17)
検索操作
(C++11)                (C++11)(C++11)
countcount_if

シーケンスを変更する操作
コピー操作
(C++11)
(C++11)
スワップ操作
変換操作
生成操作
削除操作
順序変更操作
(C++17まで)(C++11)
(C++20)(C++20)
サンプリング操作
(C++17)

ソートおよび関連操作
パーティション操作
ソート操作
二分探索操作
(パーティション化された範囲)
集合操作 (ソート済み範囲)
マージ操作 (ソート済み範囲)
ヒープ操作
最小/最大操作
(C++11)
(C++17)
辞書順比較操作
順列操作
Cライブラリ
数値演算
未初期化メモリに対する操作
 
ヘッダー <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以降)

範囲[firstlast)に含まれる要素のうち、特定の条件を満たすものの数を返します。

1) value と等しい要素を数えます(operator== を使用)。
3) 述語 ptrue を返す要素を数えます。
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以降)

目次

[edit] Parameters

first, last - 検査する要素の範囲を定義するイテレータのペア
value - 検索する値
policy - 使用する 実行ポリシー
p - 目的の要素に対して ​true を返す単項述語。

p(v) は、値カテゴリに関係なく、すべての引数 vInputIt の値型、またはその const 版)に対して bool に変換可能でなければならず、v を変更してはなりません。したがって、VT& のようなパラメータ型は許可されません。また、VT がムーブがコピーと同等でない限り、VT も同様です。(C++11 以降)

型要件
-
InputItLegacyInputIterator の要件を満たす必要があります。
-
ForwardItLegacyForwardIterator の要件を満たさなければなりません。
-
UnaryPredPredicate の要件を満たさなければなりません。

[edit] Return value

範囲 [firstlast) 内のイテレータ it のうち、以下の条件を満たすものの数。

1,2) *it == valuetrue
3,4) p(*it) != falsetrue である。

[edit] Complexity

std::distance(first, last)N とする

1,2) N 回、value との比較(operator== を使用)。
3,4) 述語 pN 回の適用。

[edit] Exceptions

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

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

[edit] Notes

追加の条件なしで、範囲 [firstlast) 内の要素数を取得するには、std::distance を参照してください。

機能テストマクロ 規格 機能
__cpp_lib_algorithm_default_value_type 202403 (C++26) アルゴリズム (1,2) のためのリスト初期化

[edit] Possible implementation

libstdc++ および libc++ での count の実装を参照してください。

libstdc++ および libc++ での count_if の実装を参照してください。


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;
}

[edit] Example

#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';
 
    // Determine how many integers match a target value.
    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';
    }
 
    // Use a lambda expression to count elements divisible by 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';
 
    // A simplified version of `distance` with O(N) complexity:
    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 gets deduced making list-initialization possible
        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

[edit] Defect reports

以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。

DR 適用対象 公開された動作 正しい動作
LWG 283 C++98 TEqualityComparable であることが求められていましたが、
InputIt の値型が常に T であるとは限らない
要件が削除されました

[edit] See also

2つのイテレータ間の距離を返す
(関数テンプレート) [編集]
特定の基準を満たす要素の数を返す
(アルゴリズム関数オブジェクト)[編集]
English 日本語 中文(简体) 中文(繁體)