数组/c++中的大量数字

abundance of numbers in an array/c++

本文关键字:数字 c++ 数组      更新时间:2023-10-16

如何编写程序来迭代大小为10的int数组,并输出数组中每个整数出现的次数,而不多次输出相同的整数
数组中填充了10个介于1和10之间的随机int但程序应该像程序员不知道的那样编写
禁止使用其他数组或更改给定数组的值
也禁止使用std::map。例如:

int arr[10] = {2, 2, 3, 5, 9, 1, 0, 5, 6, 4};

应输出

0:1(abundance)
1:1
2:2 
3:1
4:1
5:2
6:1
9:1

如果你可能不使用任何类型的容器,我能想到的唯一方法是:

#include <iostream>
int main(){
const size_t SZ = 10;
const int arr[SZ] = { 2, 2, 3, 5, 9, 1, 0, 5, 6, 4 };
int max = arr[0];
for(auto e : arr){
if (e > max){
max=e;
}
}
for(int i = 0; i <= max; ++i){
size_t cnt = 0;
for (auto e : arr){
if (i == e){
++cnt;
}
}
if (cnt){
std::cout << i << " : " << cnt << std::endl;
}
}
return 0;
}

这不是很有效,但考虑到你的限制,我想不出更好的方法了。

输出:

0 : 1
1 : 1
2 : 2
3 : 1
4 : 1
5 : 2
6 : 1
9 : 1