我该如何计算出现在数组多少? [英] How do I count the number of occurrences in an array?
问题描述
我已生成的5个随机整数1-5的阵列。这里是数组看起来像现在: myArray的[5] = {3,3,1,4,5}
I have generated an array of 5 random integers from 1-5. Here is what the array looks like now: myArray[5] = {3, 3, 1, 4, 5}
我现在已经整理5的整数按升序排列数组,从最低到最高。
I have now sorted the array of 5 integers in ascending order, from least to greatest.
myArray的[5] = {1,3,3,4,5}
我现在需要统计出现特定的整数拥有的数量,使得它的一个表。
I now need to count the number of occurrences a specific integer has and make a table of it.
如:
Number: Count:
1:1
2:0
3:3
4:0
5:1
我已经得到已通过数组循环最远。我有一个很难塔灵的数量和创造是如何匹配的字符串有一个计数。
The farthest I've gotten has been looping through the array. I am having a hard time talling the numbers and creating a count of how many occurances there are.
不使用任何地图,或迭代,等我试图让这个计数。以下是我已经尝试已经:
Not using any maps, or iterations, etc. I am trying to get this count. Here is what I have tried already:
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";
}
不过,我的输出是令人难以置信的错误。
However, my output is incredibly wrong.
推荐答案
使用的std ::地图
来整数映射到自己的罪名。
Use a std::map
to map integers to their counts.
std::map<int, int> counts;
for (int i = 0; i < 5; i++) {
counts[myArray[i]]++; // increment the counter for the current value
}
现在您可以打印键和值计数
。见如何通过一个C ++地图如何做这个循环。
Now you can print the keys and values in counts
. See How to loop through a c++ map for how to do this.
您可以用数组,而不是地图做。唯一的区别是,它不会自动扩展处理更大的值(除非你使用的malloc
和的realloc
制作它动态调整)。
You can do it with an array instead of a map. The only difference is that it won't automatically expand to handle larger values (unless you use malloc
and realloc
to make it dynamically sized).
#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;
}
这篇关于我该如何计算出现在数组多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!