即使srand(time(0))调用一次,std :: random_shuffle也会产生相同的结果

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().

  • 是的,我强制random_shuffle使用`rand()`以使其正常工作.而不是`random_shuffle(indices.begin(),indices.end(),rand())`,我使用`random_shuffle(begin(indices),end(indices),[](int n){return rand()% n;})`因为前一个产生错误.我使用macports安装的cmake,CXX标志-std = c ++ 11.我的g ++是clang-500.2.79,但我不知道cmake究竟使用了什么编译器. (5认同)