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

不羁岁月 提交于 2019-12-01 02:23:46

问题


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("");

}

The results are like:

850577673
246 239 7 102 41 201 288 23 1 237 

After a few seconds:

856981140
246 239 7 102 41 201 288 23 1 237 

And more:

857552578
246 239 7 102 41 201 288 23 1 237

Why the function rand() works properly but `random_shuffle' does not?


回答1:


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

An alternative would be to use random_shuffle(indices.begin(), indices.end(), rand()); because apparently your implementation of random_shuffle() is not using rand().



来源:https://stackoverflow.com/questions/22496942/stdrandom-shuffle-produce-the-same-result-even-though-srandtime0-called-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!