如何计算数组中出现的次数

How do I count the number of occurrences in an array?

本文关键字:数组 何计算 计算      更新时间:2023-10-16

我生成了一个由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++映射?了解如何做到这一点。

您可以使用数组而不是贴图来执行此操作。唯一的区别是,它不会自动扩展以处理较大的值(除非使用mallocrealloc使其动态调整大小)。

#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]是要检查的值。