如何计算数组中出现的次数
How do I count the number of occurrences in an array?
我生成了一个由1-5个随机整数组成的数组。以下是阵列现在的样子:myArray[5] = {3, 3, 1, 4, 5}
我现在已经按升序对5个整数的数组进行了排序,从最小到最大。
myArray[5] = {1, 3, 3, 4, 5}
我现在需要计算一个特定整数的出现次数,并制作一个表格
例如:
Number: Count:
1:1
2:0
3:3
4:0
5:1
我得到的最远的是在数组中循环。我很难计算出数字,也很难统计出发生了多少次。
不使用任何地图,或迭代,等等。我正在努力获得这个计数。以下是我已经尝试过的:
int counts[10];
for (int x = 0; x <= 10; x++){
int counter = 0;
for (int j = 0; j < ARRAY_SIZE; j++){
if (x == myArray[j]){
counts[x] == counter++;
}
}
cout << "Number: " << x << "Number of Occurances: " << counts[counter]<< "n";
}
然而,我的输出是错误的。
使用std::map
将整数映射到其计数。
std::map<int, int> counts;
for (int i = 0; i < 5; i++) {
counts[myArray[i]]++; // increment the counter for the current value
}
现在,您可以在counts
中打印键和值。请参阅如何循环使用C++映射?了解如何做到这一点。
您可以使用数组而不是贴图来执行此操作。唯一的区别是,它不会自动扩展以处理较大的值(除非使用malloc
和realloc
使其动态调整大小)。
#define MAX_VALUE 9
int counts[MAX_VALUE+1] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < ARRAY_SIZE; i++) {
if (myArray[i] <= MAX_VALUE) {
counts[myArray[i]]++; // increment the counter for the current value
}
}
for (int j = 0; j <= MAX_VALUE; j++) {
cout << "Number: " << j << "Number of Occurances: " << counts[j] << endl;
}
生成一个散列并用零初始化。
int hash[10000]={0};
for(int i=0;i<n;i++)
{
hash[arr[i]]++;
}
索引arr[i]处的散列将保持值,该值是该数字的出现次数。由于hash[arr[i]]++
将在等于arr[i]的值的索引处递增计数。这样,我们可以通过检查hash[arr[i]]来检查哪个值发生了多少次,其中arr[i]是要检查的值。
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++数据文件、数组和计算赋值
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 有效地计算多维数组的累积和?
- 通过指针算法计算数组长度
- 计算数组重复次数的组合的有效算法,加起来达到给定的总和
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 当我使用需要计算数组单元格地址的模板时,奇怪的C++行为
- 传递数组和计算平均C++的问题
- 如何使用二维数组来计算和存储来自其他数组的值的频率
- C++使用 getArea() 并访问数组来计算圆的面积
- 从数组中计算平均值
- c++将文本中的数字读入整数数组,计算平均值
- c++从数组中计算正数/负数的数目
- 二维数组,计算并存储6个随机连接点
- c++数组,计算函数中的重复次数
- 从四个给定的无符号字符数组中计算平均数组
- 使用结构数组进行计算