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

Foo*_*Bar 3 c++ arrays loops

我生成了一个 5 个随机整数的数组,从 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
Run Code Online (Sandbox Code Playgroud)

我得到的最远的是遍历数组。我很难计算这些数字并计算出现的次数。

不使用任何地图或迭代等。我正在尝试计算此计数。这是我已经尝试过的:

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";
}
Run Code Online (Sandbox Code Playgroud)

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

Bar*_*mar 7

使用 astd::map将整数映射到它们的计数。

std::map<int, int> counts;
for (int i = 0; i < 5; i++) {
    counts[myArray[i]]++; // increment the counter for the current value
}
Run Code Online (Sandbox Code Playgroud)

现在您可以在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;
}
Run Code Online (Sandbox Code Playgroud)