gpt4 book ai didi

c++ - random_shuffle 不是真正随机的

转载 作者:可可西里 更新时间:2023-11-01 16:26:36 26 4
gpt4 key购买 nike

我在像这样的 vector 上使用 random_shuffle:

#include <algorithm>
vector <Card> deck;
//some code to add cards to the deck here
random_shuffle ( deck.begin(), deck.end() );

运行的时候deck的内容是乱码的,但是重启程序后还是保留了这个乱码。

我错过了什么吗?我怎样才能让它真正随机?

最佳答案

您需要先使用 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.

关于c++ - random_shuffle 不是真正随机的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13459953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com