c++检查数组中的重复项并替换它们

C++ check array for duplicates and replace them

本文关键字:替换 检查 数组 c++      更新时间:2023-10-16

我有一个充满值的数组,该数组不能包含任何重复的值。对于任何重复的值,将值加1。这里是代码我有到目前为止,但我仍然得到重复。(randArray是值所在的位置)。

for (int i = 0; i < sizeof(randArray) - 1; i++) {
    for (int j = sizeof(randArray); j == 0; j--) {
        if (randArray[i] == randArray[j]) {
            randArray[i] == randArray[i] + 1;
        }
    }
}

您在增加副本时出现了打字错误:

     randArray[i] = randArray[i] + 1; // not ==

同样,增量可能会创建另一个副本。如果是后面的项目,没有问题。但是由于数组没有排序,您可能无法捕获已经传递的值的新副本。

因此您可能需要多次传递:

 bool wasaninc;
 do {
      wasaninc=false;
      for ...
          for ...
              ... // if there is an increment, set wasaninc to true
  } while (wasaninc);
Change  randArray[i] == randArray[i] + 1; to randArray[i] = randArray[i] + 1;
   for (int i = 0; i < sizeof(randArray) - 1; i++) {
        for (int j = sizeof(randArray); j == 0; j--) {
            if (randArray[i] == randArray[j]) {
                randArray[i] = randArray[i] + 1;
            }
        }
    }

您的问题是由于sizeof(randArray)。这个方法不返回数组中元素的个数。

例如:

int array[5] = { 1, 2, 3, 4, 5};
sizeof(array);   // -> returns 20, because of 5 * 4 bytes (integer = 4 bytes)

不应该使用这个方法,而应该使用数组中元素的个数。您已经在开始时声明了数组的大小。因此,数组中可以有多少个元素就很清楚了。

正确的例子:

int array[100] = {...};
for (int i = 0; i < 99; i++) {
     for (int j = 0; j < 99; j++) {
          if (array[i] == array[j]) {
              // code for duplicates
          }
      }
}

#include <iostream>
#include <unistd.h>
#include <algorithm>
using namespace std;
int main()
{
    int arr[8]={0,1,1};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout<<n<<"n";
  
    /*Here we take two parameters, the beginning of the
    array and the length n upto which we want the array to
    be sorted*/
    //sort(arr, arr + n);
    for (int i=0;i<=n;i++){
        cout<<arr[i]<<" ";
    }
    int result=0;
    do{
        for (int i=0;i<=n;i++){
            for (int j =0;j<i;j++){
                if(arr[j]==arr[i]){
                    srand(time(NULL)); // Seed the time
                    int finalNum = rand()%((10-1)+1); // Generate the number, assign to variable.
                    arr[i] = finalNum;
                    result = result + 1;
                    sleep(1);
                    i--;
                    
                }
            }
        }
    }
    while(result<=2);
    n = sizeof(arr) / sizeof(arr[0]);
  
    /*Here we take two parameters, the beginning of the
    array and the length n upto which we want the array to
    be sorted*/
    //sort(arr, arr + n);
    cout<<"n";
    for (int i=0;i<=n;i++){
        cout<<arr[i]<<" ";
    }
    return 0;
}

(我假设randArray是一个c风格的数组) sizeof(randArray) 返回数组中元素的数量,它返回randArray占用的字节数。

示例(在wandbox上):

int main()
{
    int arr[] = {1, 2, 3, 4};
    // Prints 16! (on my machine)
    std::cout << sizeof(arr) << "n";
}

在现代c++中使用数组的正确方法是使用std::arraystd::vector。它们都提供了一个.size()方法,返回集合中元素的个数。

你的代码失败的原因如下:

  • sizeof不返回数组中元素的个数

  • 重复元素加1不能保证它是唯一的。