我生成了一个由 1-5 中的 5 个随机整数组成的数组。这是数组现在的样子:myArray[5] = {3, 3, 1, 4, 5}
我现在已经按从小到大的升序对 5 个整数组成的数组进行了排序。
myArray[5] = {1, 3, 3, 4, 5}
我现在需要计算特定整数出现的次数并制作一个表格。
Such as:
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";
}
然而,我的输出是非常错误的。
Use a 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
. See 如何循环遍历地图的 C++ 地图?了解如何执行此操作。
您可以使用数组而不是地图来完成此操作。唯一的区别是它不会自动扩展以处理更大的值(除非您使用malloc
and 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)