在C++开发中,我们经常需要统计容器里某些元素的数量。标准库中的count和count_if函数位于algorithm头文件,能够非常方便地完成这类任务,而不需要手写循环。

count函数的基本用法
count函数用于统计容器中与给定值相等的元素个数,其函数原型为:
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> nums = {1, 2, 3, 2, 2, 4, 5};
// 统计数值2出现的次数
int cnt = std::count(nums.begin(), nums.end(), 2);
std::cout << "2出现了 " << cnt << " 次" << std::endl;
return 0;
}
上面代码中,前两个参数分别是容器的起始和结束迭代器,第三个参数是要匹配的值。返回值是匹配元素的数量,类型为迭代器差值类型,通常可转为int。
count_if函数的条件统计
当统计规则不是简单相等,而是某种条件时,就要用count_if。它接受一个谓词函数(或函数对象、lambda表达式)来判断元素是否符合条件。
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6};
// 统计大于3的元素个数
int cnt = std::count_if(nums.begin(), nums.end(), [](int x) {
return x > 3;
});
std::cout << "大于3的元素有 " << cnt << " 个" << std::endl;
return 0;
}
这里的lambda表达式[](int x){return x > 3;}就是判断条件,返回true的元素才会被计入。
在自定义类型中使用
如果是自定义结构体,count需要重载==运算符,count_if则直接在条件里写比较逻辑。
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
struct Student {
std::string name;
int score;
};
int main() {
std::vector<Student> stus = {
{"Tom", 80},
{"Lucy", 90},
{"Jim", 80}
};
// 统计分数为80的学生数量
int cnt = std::count_if(stus.begin(), stus.end(), [](const Student& s) {
return s.score == 80;
});
std::cout << "80分的学生有 " << cnt << " 人" << std::endl;
return 0;
}
使用注意事项
- count和count_if都位于<algorithm>头文件,使用前应包含。
- 对于无序且无需修改的统计,优先用这两个函数而非手写循环,可读性好。
- 在map或set等关联容器中,应注意迭代器指向的是pair或元素本身,条件写法需对应。
通过上述示例可以看出,count适合精确值统计,count_if适合灵活条件统计,合理运用能提升C++代码的简洁度和健壮性。