Daw*_*ang 6 c++ random vector srand
在函数中,我想生成范围内的数字列表:(在执行程序时,此函数仅被调用一次.)
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("");
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
850577673
246 239 7 102 41 201 288 23 1 237
Run Code Online (Sandbox Code Playgroud)
几秒钟后:
856981140
246 239 7 102 41 201 288 23 1 237
Run Code Online (Sandbox Code Playgroud)
和更多:
857552578
246 239 7 102 41 201 288 23 1 237
Run Code Online (Sandbox Code Playgroud)
为什么函数rand()正常工作但`random_shuffle'没有?
小智 6
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().