I want to generate unique random numbers and add item in function of these random numbers. Here is my code :
The problem is when i verify if the number generated exist in the array with the code results.contains(randomNb) :
int nbRandom = ui->randoomNumberSpinBox->value();
//nbRandom is the number of the random numbers we want
int i = 1;
int results[1000];
while ( i < nbRandom ){
int randomNb = qrand() % ((nbPepoles + 1) - 1) + 1;
if(!results.contains(randomNb)){
//if randomNb generated is not in the array...
ui->resultsListWidget->addItem(pepoles[randomNb]);
results[i] = randomNb;
//We add the new randomNb in the array
i++;
}
}
resultsis an array. That’s a built-in C++ type. It’s not a class type and doesn’t have methods. So this can’t work:You probably want to use a QList instead. Like:
Add elements to it with:
Also, you have an off-by-one error in the code. You start counting from 1 (
i = 1) instead of 0. This will result in missing the last number. You should change theiinitialization to:With the changes, your code would become: