首页 > 解决方案 > c++ 中的 int hash[a]={0} 有什么用,它是如何工作的?

问题描述

for(int i=0; i< a; i++){
            cin>>b;
            arr[i]=b;
        }
        int hash[100]={0}; 
        int i = 0; 
        while (i<a) 
        { 
            hash[arr[i]-1]++; 
            i++; 
        }
        int arr1[a];
        for (int i=0; i<a; i++){
            arr1[i]=hash[i]; 
        }

在这段代码中,我正在计算每个 int 的出现并将其存储在新数组中。但我不明白这个哈希是如何工作的,谁能解释一下。我不是在问数组声明。我想了解计数背后的算法。

标签: c++c++17

解决方案


这种情况下的数字0实际上是没有用的。它什么也不做,除了提醒程序员它应该做什么。

int a[100]; // creates an array, but leaves the memory uninitiated, you do not know what will be there
int b[100] {}; // creates an array and fills the memory with default values, in this case values are 0
int c[100] {0}; // creates an array, fills the first one with 0 and the rest with default values, but default values are also 0
int d[100] = {0}; // equals sign in this case is there for historical reasons, it is not an assignment operator

推荐阅读