问题描述
我有一个数组,我想改组它,我使用:
I have an array and I wish to shuffle it, I use:
answerPositionArray[0] = 100;
answerPositionArray[1] = 400;
answerPositionArray[2] = 800;
std::random_shuffle(answerPositionArray, answerPositionArray + 2);
但是,每次我运行程序时,都会出现400、800、100相同的混洗.是否有办法使混洗每次都不同?例如.第一次是100、800、400,然后是800、400、100等.
But every time I run my program the same shuffle comes out, 400, 800, 100. Is there a way to get the shuffle to be different every time? Eg. first time 100, 800, 400 then 800, 400, 100 etc.
谢谢
推荐答案
C ++随机数并不是真正的随机数-它们是由称为种子的初始值生成的.如果不设置种子,它将始终是相同的,因此生成的序列不会改变. std :: random_shuffle
取决于随机数的生成,因此它也将以这种方式运行.
C++ random numbers aren't truly random - they are generated from initial value called seed. If you don't set the seed, it will always be the same, so generated sequence won't change. std::random_shuffle
depends on random number generation, so it will behave this way as well.
那么如何设置种子呢?使用:
So how to set the seed? Use:
srand(time(0));
在使用随机数调用任何函数之前.它将种子设置为当前时间(以秒为单位).不要忘记添加适当的头文件.
before any calls to functions using random numbers. It will set the seed to current time in seconds. Don't forget to add appropritate header files.
这篇关于每次std :: random_shuffle都会产生相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!