Std :: random_shuffle produces the same result, although srand (time (0)) calls once

In a function, I want to generate a list of numbers in a range: (This function will be called only once during program execution.)

void DataSet::finalize(double trainPercent, bool genValidData) { srand(time(0)); printf("%d\n", rand()); // indices = {0, 1, 2, 3, 4, ..., m_train.size()-1} vector<size_t> indices(m_train.size()); for (size_t i = 0; i < indices.size(); i++) indices[i] = i; random_shuffle(indices.begin(), indices.end()); // Output for (size_t i = 0; i < 10; i++) printf("%ld ", indices[i]); puts(""); } 

The results are as follows:

 850577673 246 239 7 102 41 201 288 23 1 237 

In a few seconds:

 856981140 246 239 7 102 41 201 288 23 1 237 

And further:

 857552578 246 239 7 102 41 201 288 23 1 237 

Why does the rand() function work correctly, but `random_shuffle 'does not work?

+6
source share
1 answer

random_shuffle() is not actually used to use rand() , and therefore srand() may not have any effect. If you want to be sure, you should use one of the forms C ++ 11, random_shuffle(b, e, RNG) or shuffle(b, e, uRNG) .

An alternative would be to use random_shuffle(indices.begin(), indices.end(), rand()); , because apparently your implementation of random_shuffle() does not use rand() .

+5
source

All Articles