c/c++语言开发共享如何检查数组是否有任何重复?

我正在将文件的内容读入9元素数组。 我需要检查这个数组中是否有任何重复项。 我需要这样做而无需重新排序或更改数组的任何内容。

我该怎么做呢?

    使用蛮力。

    你在数组中只有9个元素,因此只需要进行36次比较就可以找到任何重复项:

    int count = sizeof(array) / sizeof(array[0]); for (int i = 0; i < count - 1; i++) { // read comment by @nbro for (int j = i + 1; j < count; j++) { if (array[i] == array[j]) { // do whatever you do in case of a duplicate } } } 

    您可以使用此方法:

     // sort a copy of the array with the algorithm you like the most and then... bool duplicates = false; for(i = 0; i < 7; i++) { if (array[i] == array[i+1]) { duplicates = true; break; } } 

      int main() { srand(time(0)); int data[10]; for(int c=0;c<=9;c++) { bool found = false; while(!found) { data[c]=rand()%10+1; found=true; for(int r=0;r 

      以上就是c/c++开发分享如何检查数组是否有任何重复?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/560607.html

      (0)
      上一篇 2021年1月28日
      下一篇 2021年1月28日

      精彩推荐