c++ - 该声明的含义 count[array[i]]

标签 c++ c

谁能解释一下下面程序中的 count[array[i]] 是什么意思? 代码的目的是打印数组中所有重复的数字和频率。

#include <stdio.h>
#include <malloc.h>

void duplicate(int array[], int num)
{
    int *count = (int *)calloc(sizeof(int), (num - 2));
    int i;

    printf("duplicate elements present in the given array are ");
    for (i = 0; i < num; i++)
    {
        if (count[array[i]] == 1)
            printf(" %d ", array[i]);
        else
            count[array[i]]++;
    }
}

int main()
{
    int array[] = {5, 10, 10, 2, 1, 4, 2};
    int array_freq = sizeof(array) / sizeof(array[0]);
    duplicate(array, array_freq);
    getchar();
    return 0;
}

最佳答案

这是用于查找数组中重复项的最糟糕的方法。

count[array[i]]++;

因此,array[i] 将返回该索引处的数字,该数字又将用作 count 数组的索引。例如:-

array[4] = {1,2,3,1};

将数组迭代到此将类似于:-

count[array[0]] = count[1] = 1;
count[array[1]] = count[2] = 1;
count[array[2]] = count[3] = 1;
count[array[3]] = count[1] = 2; << Increment the count...

关于c++ - 该声明的含义 count[array[i]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27089023/

相关文章:

c++ - 如何遍历/迭代 STL 映射?

c++ - 如何在 GMP 的 while 循环中获得不相等

c - 如何通过系统调用将C中的数组从内核返回给用户

c - 重定向错误仅发生在 "ls"命令上。其他命令重定向得很好。我的代码有什么问题吗?

c++ - Rummikub 算法

c++ - 为 c++20 编写输出迭代器

c++ - 使用 Bazel 分离编译和链接操作

c - 在C中将数字数组乘以int

c - 当 sizeof(int) == 4 时,1 << 31 在 C 中是否定义明确

使用 cryptoauthlib 配置 ATEC608A