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 ) 必须可转换为 bool ,其中每个参数 v 的类型为(可能为const的) VT VT InputIt 的值类型),且与值类别无关,同时不能修改 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) 使用 operator == value 进行恰好 N 次比较。
3,4) 恰好应用谓词 p N 次。

异常

带有名为 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';
    }
    // 使用 lambda 表达式统计可被 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++标准。

缺陷报告 应用于 发布时行为 正确行为
LWG 283 C++98 T 被要求满足 EqualityComparable 要求,但
InputIt 的值类型并不总是 T
移除了该要求

参见

返回两个迭代器之间的距离
(函数模板)
返回满足特定条件的元素数量
(算法函数对象)