c++里的count函数
时间: 2024-10-17 09:07:32 浏览: 53
在C++中,`std::count()`是一个算法函数,它属于 `<algorithm>` 头文件的一部分。这个函数用于计算某个给定值在输入范围(如容器、数组或其他迭代序列)中出现的次数。其基本语法是:
```cpp
template <class InputIterator, class T>
size_t count(InputIterator first, InputIterator last, const T& value);
```
其中:
- `InputIterator` 是指向输入序列中元素的迭代器类型。
- `last` 是迭代器,表示输入范围的结束位置(不包括)。
- `value` 是你要查找的特定值。
这个函数返回从 `first` 到 `last` 区间内找到的 `value` 的实例数目。例如,如果你有一个整数向量,并想找出某个整数值出现了多少次,可以这样做:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 2, 6, 2};
int target = 2;
size_t count = std::count(numbers.begin(), numbers.end(), target);
std::cout << "Number " << target << " appears " << count << " times." << std::endl;
return 0;
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)