C++STL---count() 统计容器中特定元素出现次数
在 C++ 标准库中,count
是一个用于统计容器中特定元素出现次数的函数,定义在 <algorithm>
头文件中。它可以快速计算某个值在容器(如数组、vector、list 等)中出现的次数,避免手动编写循环计数的麻烦。
一、函数原型
count
函数有两种常用形式(以 vector<int>
为例):
// 1. 统计 [first, last) 范围内等于 value 的元素个数
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count(InputIterator first, InputIterator last, const T& value);
- 参数说明:
first
:容器的起始迭代器(指向要统计的范围的第一个元素)。last
:容器的结束迭代器(指向要统计的范围的最后一个元素的下一个位置)。value
:要统计出现次数的目标值。
- 返回值:目标值
value
在[first, last)
范围内出现的次数(类型为迭代器的差值类型,通常可视为int
)。
二、使用场景与示例
count
函数适用于所有支持迭代器的容器(如 vector
、array
、list
、string
等),核心作用是快速统计特定元素的出现次数。
示例 1:统计 vector 中特定元素的次数
#include <iostream>
#include <vector>
#include <algorithm> // 必须包含此头文件using namespace std;int main() {vector<int> nums = {1, 2, 3, 2, 4, 2, 5};int target = 2;// 统计 nums 中 2 出现的次数int cnt = count(nums.begin(), nums.end(), target);cout << "数字 " << target << " 出现了 " << cnt << " 次" << endl;// 输出:数字 2 出现了 3 次return 0;
}
示例 2:统计数组中特定元素的次数
#include <iostream>
#include <algorithm>using namespace std;int main() {int arr[] = {5, 3, 5, 7, 5, 9};int n = sizeof(arr) / sizeof(arr[0]); // 数组长度int target = 5;// 统计数组中 5 出现的次数(用指针作为迭代器)int cnt = count(arr, arr + n, target);cout << "数字 " << target << " 出现了 " << cnt << " 次" << endl;// 输出:数字 5 出现了 3 次return 0;
}
示例 3:统计字符串中特定字符的次数
#include <iostream>
#include <string>
#include <algorithm>using namespace std;int main() {string s = "hello world";char target = 'l';// 统计字符串中 'l' 出现的次数int cnt = count(s.begin(), s.end(), target);cout << "字符 '" << target << "' 出现了 " << cnt << " 次" << endl;// 输出:字符 'l' 出现了 3 次return 0;
}
三、工作原理
count
函数的内部逻辑其实很简单,相当于一个「自动循环计数」的过程:
- 从
first
迭代器开始,遍历到last
迭代器(不包含last
指向的位置)。 - 每遇到一个与
value
相等的元素,就将计数加 1。 - 遍历结束后,返回总计数。
可以理解为它替我们实现了这样的手动循环:
// 手动模拟 count 函数的逻辑
int manual_count(vector<int>& nums, int value) {int cnt = 0;for (int x : nums) {if (x == value) cnt++;}return cnt;
}
四、注意事项
-
必须包含头文件
使用count
函数前,必须包含<algorithm>
头文件,否则会编译错误。 -
范围是左闭右开
函数的统计范围是[first, last)
,即包含first
指向的元素,但不包含last
指向的元素。例如:vector<int> nums = {1,2,3,4,5}; // 只统计前3个元素(1,2,3)中 2 出现的次数 int cnt = count(nums.begin(), nums.begin() + 3, 2); // 结果为 1
-
元素必须支持
==
比较
count
函数通过==
运算符判断元素是否相等,因此容器中的元素类型必须支持==
操作(如基本类型int
、char
,或自定义类型重载了==
运算符)。 -
时间复杂度
count
函数需要遍历整个范围[first, last)
,时间复杂度为 O(n)(n 是范围中元素的个数),与手动循环计数效率相同,但代码更简洁。 -
哈希表的count()
unordered_map::count(key)
的返回值只有两种可能:0
(键不存在)或1
(键存在)。
这是因为unordered_map
中不允许存在重复的键(每个键唯一对应一个值),所以「键的出现次数」要么是 0(不存在),要么是 1(存在)。
五、与 count_if
的区别
标准库中还有一个类似的函数 count_if
,用于统计满足特定条件的元素个数(而非等于某个固定值)。例如:
// 统计 nums 中大于 3 的元素个数
vector<int> nums = {1,2,3,4,5,6};
int cnt = count_if(nums.begin(), nums.end(), [](int x) { return x > 3; });
// 结果为 3(4,5,6 满足条件)
count
适用于「等于某个值」的简单统计;count_if
适用于「满足自定义条件」的复杂统计(需传入一个判断条件的函数或 lambda 表达式)。