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

std::random_shuffle produce the same result even though srand(time(0)) called once

本文关键字:结果 time 一次 shuffle 调用 random Std srand      更新时间:2023-10-16

在一个函数中,我想生成一个范围内的数字列表:(这个函数在执行程序时只会被调用一次)

void DataSet::finalize(double trainPercent, bool genValidData)
{
    srand(time(0));
    printf("%dn", 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()