C++ 标准库 - <algorithm>

C++ std::count_if 对每个元素调用谓词,统计使谓词为真的个数。

原型

template<class InputIt, class UnaryPredicate>
typename iterator_traits<InputIt>::difference_type
count_if(InputIt first, InputIt last, UnaryPredicate p);

参数

  • first, last:统计区间。
  • p:一元谓词。

返回值

满足条件的元素个数。

示例

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1, 3, 8, 5, 4};
    auto n = std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
    std::cout << n << std::endl;
    return 0;
}

输出:

2

注意事项

谓词捕获外部变量时注意生命周期与线程安全。只需要是否存在满足条件的元素时,优先 find_if。

下一页介绍copy:复制区间。