C++ 如何在同一程序/函数中每次生成不同的随机数集?
我知道,使用srand(time(0))有助于设置随机种子。但是,下面的代码为两个不同的列表存储相同的数字集 想知道,当下面的函数被多次调用时,如何生成不同的数字集C++ 如何在同一程序/函数中每次生成不同的随机数集?,c++,stl,random,C++,Stl,Random,我知道,使用srand(time(0))有助于设置随机种子。但是,下面的代码为两个不同的列表存储相同的数字集 想知道,当下面的函数被多次调用时,如何生成不同的数字集 void storeRandomNos(std::list<int>& dataToStore) { int noofElements = 0; srand(time(0)); noofElements = (rand() % 14 ) + 1; while ( noofE
void storeRandomNos(std::list<int>& dataToStore)
{
int noofElements = 0;
srand(time(0));
noofElements = (rand() % 14 ) + 1;
while ( noofElements --)
{
dataToStore.push_back(rand() % 20 + 1 );
}
}
void storeRandomNos(标准::列表和数据存储)
{
int noofElements=0;
srand(时间(0));
noofElements=(rand()%14)+1;
而(noofElements--)
{
dataToStore.push_back(rand()%20+1);
}
}
下面是代码的其余部分
void printList(const std::list<int>& dataElements, const char* msg);
void storeRandomNos(std::list<int>& dataToStore);
int main()
{
std::list<int> numberColl1;
std::list<int> numberColl2;
storeRandomNos(numberColl1);
storeRandomNos(numberColl2);
printList(numberColl1 , "List1");
printList(numberColl2 , "Second list");
}
void printList(const std::list<int>& dataElements, const char* msg)
{
std::cout << msg << std::endl;
std::list<int>::const_iterator curLoc = dataElements.begin();
for ( ; curLoc != dataElements.end() ; ++curLoc)
{
std::cout << *curLoc << ' ';
}
}
void打印列表(const std::list&dataElements,const char*msg);
void storeRandomNos(标准::列表和数据存储);
int main()
{
std::列表编号coll1;
std::列表编号COLL2;
storeRandomNos(编号Coll1);
storeRandomNos(numberColl2);
打印列表(numberColl1,“列表1”);
打印列表(numberColl2,“第二个列表”);
}
无效打印列表(常量std::list&dataElements,常量char*msg)
{
std::cout在程序开始时执行一次srand(time(0))
。仅在主程序启动时初始化RNG一次。不是每次进入函数时都进行初始化。否则,函数很可能在同一秒内调用两次,这可能会为time(0)提供相同的结果
伪随机生成器(如rand()
)只是一个数学函数,它接受一个输入(种子)并对其进行一些处理。它返回它产生的新值,并将其设置为新种子。下次它将使用该新种子值
因为计算机是确定性的,每次你用相同的种子调用rand()
,它都会产生相同的输出值。这就是为什么它是伪随机的
在您的示例中,您使用了两次相同的种子,因为time(0)
以秒为单位返回时间,并且您的两个函数调用在同一秒内发生(因为计算机速度非常快)
正如其他评论者所说,只需将种子设定为一个相当随机的值(即当前时间)一次。您需要在程序中调用rand()
以获得伪随机数的每个线程中只使用srand(时间(0))
一次。感谢您的详细解释。