std :: random_shuffle产生相同的结果,即使srand(time(0))调用一次 [英] std::random_shuffle produce the same result even though srand(time(0)) called once
问题描述
在函数中,我想生成范围内的数字列表:
(此函数在执行程序时只会调用一次。)
In a function, I want to generate a list of numbers in range: (This function will be called only once when executing the program.)
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("");
}
结果如下:
850577673
246 239 7 102 41 201 288 23 1 237
几秒钟后:
856981140
246 239 7 102 41 201 288 23 1 237
等等:
857552578
246 239 7 102 41 201 288 23 1 237
为什么函数 rand()
可以正常工作,但`random_shuffle'不会?
Why the function rand()
works properly but `random_shuffle' does not?
推荐答案
random_shuffle()
实际上并未指定使用 rand()
code> srand()可能没有任何影响。如果你想确定,你应该使用C ++ 11中的一种形式, random_shuffle(b,e,RNG)
或 shuffle ,e,uRNG)
。
random_shuffle()
isn't actually specified to use rand()
and so srand()
may not have any impact. If you want to be sure, you should use one of the C++11 forms, random_shuffle(b, e, RNG)
or shuffle(b, e, uRNG)
.
另一种方法是使用 random_shuffle(indices.begin因为显然你的实现
random_shuffle()
没有使用 rand()
/ code>。
An alternative would be to use random_shuffle(indices.begin(), indices.end(), rand());
because apparently your implementation of random_shuffle()
is not using rand()
.
这篇关于std :: random_shuffle产生相同的结果,即使srand(time(0))调用一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!