答案:使用std::count可统计vector中元素出现次数。包含头文件后,调用std::count(vec.begin(), vec.end(), target)即可统计目标值在vector中的频次,适用于int、string等类型,时间复杂度O(n),适合小到中等规模数据。

在C++中,可以使用标准库中的 std::count 函数来统计 vector 中某个元素出现的次数。这个函数定义在
使用 std::count 统计元素个数
std::count 接收两个迭代器(表示范围)和一个目标值,返回该值在范围内出现的次数。
示例代码:
#include <iostream>
#include <vector>
#include <algorithm> // std::count
int main() {
std::vector<int> vec = {1, 2, 3, 2, 4, 2, 5};
int target = 2;
int count = std::count(vec.begin(), vec.end(), target);
std::cout << "元素 " << target << " 出现了 " << count << " 次。\n";
return 0;
}
输出结果:
需要创建、读取、编辑或处理 Word 文档(.docx / .dotx)时使用。触发词:'Word'、'word 文档'、'.docx'、'生成报告'、'制作合同/简历/方案/说明书'、'提取 word 内容'、'在文档里查找替换'、'给文档加页眉页脚/目录/表格'。也用于把任意内容排版成一份正式的 Word 文件。不要用它处理 PDF、Excel 或无关编程任务。中文创作场景尤其适合:小说大纲稿、投稿文档、合同、简历、工作总结。
立即学习“C++免费学习笔记(深入)”;
元素 2 出现了 3 次。适用于其他数据类型
std::count 不仅适用于整数,还可以用于字符串、字符等类型。
例如统计字符串 vector 中某个字符串的出现次数:
std::vector<std::string> words = {"apple", "banana", "apple", "cherry", "apple"};
std::string key = "apple";
int n = std::count(words.begin(), words.end(), key);
std::cout << "单词 '" << key << "' 出现了 " << n << " 次。\n";
注意事项
- 确保已包含
头文件。 - std::count 是线性遍历,时间复杂度为 O(n),适合小到中等规模的数据。
- 如果需要频繁查询多个元素的出现次数,可考虑使用 std::map 或 std::unordered_map 预先统计频次。


















