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

时间:2015-02-14 01:47:02

标签: c++ arrays loops

我已经从1-5生成了一个包含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";
}

但是,我的输出非常错误。

2 个答案:

答案 0 :(得分:4)

使用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中打印键和值。有关如何执行此操作,请参阅How to loop through a C++ map of maps?

您可以使用数组而不是地图来执行此操作。唯一的区别是它不会自动扩展以处理更大的值(除非您使用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;
}

答案 1 :(得分:0)

进行散列并以零初始化。

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]是要检查的值)来检查哪个值出现了几次。