在一个函数中,我想生成一个范围内的数字列表: (该函数只会在程序执行时被调用一次。)
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' 却不能?
最佳答案
random_shuffle()
实际上并未指定使用 rand()
,因此 srand()
可能没有任何影响。如果您想确定,您应该使用 C++11 形式之一,random_shuffle(b, e, RNG)
或 shuffle(b, e, uRNG)
.
另一种方法是使用 random_shuffle(indices.begin(), indices.end(), rand());
因为显然你的 random_shuffle()
实现没有使用 rand()
。
关于c++ - std::random_shuffle 产生相同的结果,即使 srand(time(0)) 被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22496942/