std::count
是C++标准库中的一个算法,用于计算给定值在指定范围内出现的次数。它的原型如下:
template
size_t count(InputIt first, InputIt last, const T& value);
其中,first
和last
表示范围的起始和结束迭代器,value
表示要查找的值。函数返回一个size_t
类型的值,表示value
在指定范围内出现的次数。
std::count
函数在以下场景中非常有用:
#include
#include
#include
int main() {
std::vector 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.
#include
#include
#include
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.
#include
#include
#include
#include
int main() {
std::vector 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 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.
std::count
函数是一个非常实用的算法,它可以帮助我们快速统计给定值在指定范围内的出现次数。无论是统计数组、字符串还是容器中的元素出现次数,都可以使用std::count
函数轻松实现。