名稱空間
變體
操作

std::count, std::count_if

來自 cppreference.com
< cpp‎ | 演算法
 
 
演算法庫
有約束演算法與針對範圍的演算法 (C++20)
有約束的演算法,例如 ranges::copyranges::sort 等……
執行策略 (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) 計數謂詞 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 起)

目錄

[edit] 引數

first, last - 定義要檢查的元素範圍的迭代器對
value - 要搜尋的值
policy - 要使用的 執行策略
p - 一元謂詞,對於符合要求的元素返回true

對於型別為(可能為 const)VT(其中VTInputIt的值型別)的每個引數v,表示式p(v)必須可轉換為bool,而無論值類別如何,並且不得修改v。因此,不允許使用引數型別VT&,也不允許使用VT,除非對於VT移動等同於複製(自 C++11 起)

型別要求
-
InputIt 必須滿足 LegacyInputIterator 的要求。
-
ForwardIt 必須滿足 LegacyForwardIterator 的要求。
-
UnaryPred 必須滿足 Predicate 的要求。

[edit] 返回值

範圍[firstlast) 中滿足以下條件的迭代器 it 的數量:

1,2) *it == valuetrue
3,4) p(*it) != falsetrue

[edit] 複雜度

給定 N 作為 std::distance(first, last)

1,2) 恰好 N 次使用 operator==value 進行比較。
3,4) 恰好 N 次應用謂詞 p

[edit] 異常

帶有模板引數 ExecutionPolicy 的過載按如下方式報告錯誤

  • 如果作為演算法一部分呼叫的函式執行時丟擲異常,並且ExecutionPolicy標準策略之一,則呼叫std::terminate。對於任何其他ExecutionPolicy,行為是實現定義的。
  • 如果演算法未能分配記憶體,則丟擲 std::bad_alloc

[edit] 注意

有關範圍 [firstlast) 中不帶任何附加條件的元素數量,請參閱 std::distance

特性測試 標準 特性
__cpp_lib_algorithm_default_value_type 202403 (C++26) 演算法的列表初始化 (1,2)

[edit] 可能實現

另請參閱 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] 示例

#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] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 283 C++98 要求 TEqualityComparable,但
InputIt 的值型別並不總是 T
移除了此要求

[edit] 另請參閱

返回兩個迭代器間的距離
(函式模板) [編輯]
返回滿足特定條件的元素數量
(演算法函式物件)[編輯]