2010-08-06 40 views
2

我明白,使用srand(时间(0)),有助于设置随机种子。但是,下面的代码为两个不同的列表存储相同的一组数字。如何在同一个程序/函数中每次生成不同的随机数字集?

想知道,当以下函数被多次调用时,如何生成不同的数字集合。

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 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 << ' '; 
    } 
} 

回答

2

在您的程序开始时执行一次srand(time(0))

+0

感谢您的解决方案。 – user373215 2010-08-06 12:42:25

6

当主程序启动时,仅初始化一次RNG。不是每次你进入你的功能。否则,可能在同一秒内调用两次函数,这可能会给你time(0)的相同结果。

+0

感谢您的解决方案。 – user373215 2010-08-06 12:41:42

8

一个伪随机发生器,如rand(),只是一个数学函数,它接受一个输入 - 种子 - 并对其进行一些处理。它返回它产生的新值,并将其设置为新种子。下一次它将使用新的种子值。

因为计算机是确定性的,所以每次用相同的种子调用rand()时,它会产生相同的输出值。这就是为什么它是随机。

在你的例子中,你使用了两次相同的种子,因为time(0)以秒为单位返回时间,而你的两个函数调用发生在同一秒内(因为电脑速度很快)。

正如其他评论者所说,只需要一次种子到相当随机的值(即当前时间)。

+0

感谢您的详细解释。 – user373215 2010-08-06 12:41:01

0

您需要使用srand(time(0))每个线程,在你的计划,让伪随机号码的呼叫rand()一次。

相关问题