写一个c++可以统计数字在某数字中出现次数的函数
时间: 2025-02-17 14:23:09 浏览: 13
在C++中,你可以创建一个名为countOccurrences
的函数,该函数接收两个整数参数:一个是包含所有数字的数组arr
,另一个是要查找频率的目标数字targ
。下面是一个简单的模板示例,展示了如何实现这个功能:
#include <iostream>
#include <vector>
// 函数声明
int countOccurrences(const std::vector<int>& arr, int targ);
// 主函数示例
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 2, 3, 2};
int target = 2;
int occurrences = countOccurrences(numbers, target);
std::cout << "Number " << target << " appears " << occurrences << " times in the array." << std::endl;
return 0;
}
// 实现函数
int countOccurrences(const std::vector<int>& arr, int targ) {
int count = 0;
for (const auto& num : arr) {
if (num == targ) {
count++;
}
}
return count;
}
这个函数通过遍历输入数组arr
,每当遇到目标数字targ
就计数器加一,最后返回计数器的值,即目标数字在数组中出现的次数。
相关推荐


















