我明白,使用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 << ' ';
}
}
感謝您的解決方案。 – user373215 2010-08-06 12:42:25