我在这样一个向量上使用random_shuffle:
#include <algorithm> vector <Card> deck; //some code to add cards to the deck here random_shuffle ( deck.begin(),deck.end() );
运行时,甲板的内容会混合起来,但是当我重新启动程序时,会保留这个混合顺序.
我错过了什么?如何让它真正随机?
解决方法
您需要使用
srand先播放伪随机数生成器.
#include <algorithm> #include <cstdlib> ... std::srand(std::time(0)); vector <Card> deck; //some code to add cards to the deck here random_shuffle ( deck.begin(),deck.end() );
从以上链接注意:
Generally speaking,the pseudo-random number generator should only be seeded once,before any calls to rand(),and the start of the program. It should not be repeatedly seeded,or reseeded every time you wish to generate a new batch of pseudo-random numbers.