【发布时间】:2019-08-07 04:31:51
【问题描述】:
我想生成一个小于 10 的随机整数列表,它们不一样(不同的整数),例如(0,3,1,5,8)。 但是我写的代码有问题,前两个整数总是相同的。 如果你的代码告诉我我的代码的错误或提供另一种方法来做到这一点,那就太好了。
vector<int> rand_list(10, 11); //there is ten integers of 11
for (int i = 0; i < 5; i++) // here we make 5 different integers
{
srand(time(NULL));
int r = rand() % 10;
int check = 0;
for (check; check <= i; check++)
{
if (r == rand_list[check])
{
srand(time(NULL));
r = rand() % 10;
check = 0;//I think this line don't force the second loop for to start again.
}
}
rand_list[i] = r;
}
这里我希望 rand_list 有 5 个不同的整数,其他项目必须是 11,但前两个整数总是相同的!
【问题讨论】:
-
您可能想在开始之前播种一次。
-
You may find
std::shuffle在分配要求没有禁止的情况下在这里很有用。如果他们有,请窃取这个想法。 -
你也可以简单地用
0..10填充一个向量v,然后,5次,在0..v.size()-1中选择一个随机索引,将该索引处的值添加到你的结果中,然后删除它向量中的元素。