std::count 函数
1. 函数介绍
std::count
是C++标准库中的一个算法,用于计算给定值在指定范围内出现的次数。它的原型如下:
template <class InputIt, class T> size_t count(InputIt first, InputIt last, const T& value);
其中,first
和last
表示范围的起始和结束迭代器,value
表示要查找的值。函数返回一个size_t
类型的值,表示value
在指定范围内出现的次数。
2. 使用场景
std::count
函数在以下场景中非常有用:
2.1 统计数组中某个元素的出现次数
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> nums = {1, 2, 3, 4, 5, 2, 3, 2}; int target = 2; size_t count = std::count(nums.begin(), nums.end(), target); std::cout << "The number " << target << " appears " << count << " times in the array." << std::endl; return 0; }
输出结果:
The number 2 appears 3 times in the array.
2.2 统计字符串中某个字符的出现次数
#include <iostream> #include <string> #include <algorithm> int main() { std::string str = "hello world"; char target = 'l'; size_t count = std::count(str.begin(), str.end(), target); std::cout << "The character '" << target << "' appears " << count << " times in the string." << std::endl; return 0; }
输出结果:
The character 'l' appears 3 times in the string.
2.3 统计容器中某个元素的出现次数
#include <iostream> #include <vector> #include <algorithm> #include <set> int main() { std::vector<int> nums = {1, 2, 3, 4, 5, 2, 3, 2}; int target = 2; size_t count = std::count(nums.begin(), nums.end(), target); std::cout << "The number " << target << " appears " << count << " times in the vector." << std::endl; std::set<int> s = {1, 2, 3, 4, 5, 2, 3, 2}; count = std::count(s.begin(), s.end(), target); std::cout << "The number " << target << " appears " << count << " times in the set." << std::endl; return 0; }
输出结果:
The number 2 appears 3 times in the vector. The number 2 appears 3 times in the set.
3. 总结
std::count
函数是一个非常实用的算法,它可以帮助我们快速统计给定值在指定范围内的出现次数。无论是统计数组、字符串还是容器中的元素出现次数,都可以使用std::count
函数轻松实现。
本文作者:胖柚の工作室
本文链接:https://www.cnblogs.com/pangyou3s/p/18148870
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步