count统计等于指定值的元素个数,如std::count(nums.begin(), nums.end(), 2)返回2的出现次数;count_if通过条件函数或lambda统计满足条件的元素个数,如统计偶数或大于某值的元素,需传入返回布尔值的可调用对象。

在C++中,count 和 count_if 是标准模板库(STL)中定义在 algorithm 头文件中的两个常用函数,用于统计容器中满足特定条件的元素个数。它们使用简单、效率高,适合对数组、vector、list等容器进行快速计数。
count:统计等于特定值的元素个数
count 用于统计区间内与指定值相等的元素数量。其基本语法如下:
count(起始迭代器, 结束迭代器, 目标值)它会遍历从起始到结束(前闭后开)的范围,返回等于目标值的元素个数。
示例:
立即学习“C++免费学习笔记(深入)”;
#include#include
#include iostream>
int main() {
std::vector
int cnt = std::count(nums.begin(), nums.end(), 2);
std::cout return 0;
}
count\_if:统计满足自定义条件的元素个数
当你需要根据某个条件(比如大于某值、为奇数、字符串长度超过5等)来统计时,就要用 count_if。它的语法是:
count_if(起始迭代器, 结束迭代器, 条件函数/lambda表达式)第三个参数是一个可调用对象(函数指针、函数对象或lambda),返回布尔值,表示当前元素是否满足条件。
示例:统计偶数个数
#include#include
#include
int main() {
std::vector
int even_count = std::count_if(nums.begin(), nums.end(),
[](int n) { return n % 2 == 0; });
std::cout return 0;
}
更多条件示例:
- 统计大于5的元素:
[](int n){ return n > 5; } - 统计字符串长度大于3的个数:
std::count_if(strs.begin(), strs.end(), [](const std::string& s) { return s.length() > 3; }); - 判断是否为正数:
[](double x) { return x > 0; }
使用要点与注意事项
- 记得包含头文件:#include
- 适用于所有支持迭代器的容器:vector、array、list、deque 等
- count 使用 == 运算符比较,因此类型必须支持该操作
- count_if 的条件函数应尽量简洁高效,避免副作用
- 可以结合 lambda 表达式实现复杂逻辑,代码更清晰










