您的位置:首页 >C++统计vector元素出现次数方法
发布于2025-11-11 阅读(0)
扫一扫,手机访问
答案:使用std::count可统计vector中元素出现次数。包含<algorithm>头文件后,调用std::count(vec.begin(), vec.end(), target)即可统计目标值在vector中的频次,适用于int、string等类型,时间复杂度O(n),适合小到中等规模数据。

在C++中,可以使用标准库中的 std::count 函数来统计 vector 中某个元素出现的次数。这个函数定义在 <algorithm> 头文件中。
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;
}
输出结果:
元素 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";
上一篇:杏皮水自制教程简单易学
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9