#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// 创建一个整数向量
std::vector<int> numbers = {1, 2, 3, 4, 5, 2, 6, 2};
// 使用 std::count 统计向量中值为 2 的元素个数
int count_of_twos = std::count(numbers.begin(), numbers.end(), 2);
// 输出结果
std::cout << "The number of twos in the vector is: " << count_of_twos << std::endl;
return 0;
}
#include <iostream>
和 #include <vector>
:引入标准输入输出库和向量容器库。#include <algorithm>
:引入算法库,其中包含 std::count
函数。std::vector<int> numbers
:创建一个整数向量,并初始化一些数据。std::count(numbers.begin(), numbers.end(), 2)
:使用 std::count
函数统计向量中值为 2 的元素个数。numbers.begin()
和 numbers.end()
分别表示向量的起始和结束迭代器。std::cout
:输出统计结果到控制台。这段代码展示了如何使用 C++ 标准库中的 std::count
函数来统计容器中特定元素的出现次数。
上一篇:c++小数点后保留两位数
下一篇:mutable在c++中的作用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站