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

在C++中,可以使用标准库中的 std::count 函数来统计 vector 中某个元素出现的次数。这个函数定义在 red"><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;
}
输出结果:
立即学习“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";
以上就是c++++中如何统计vector中某个元素的个数_c++ vector统计元素出现次数的详细内容,更多请关注php中文网其它相关文章!
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号