数组/c++中的大量数字
abundance of numbers in an array/c++
如何编写程序来迭代大小为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
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组