代码之家  ›  专栏  ›  技术社区  ›  Dawei Yang

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

  •  6
  • Dawei Yang  · 技术社区  · 12 年前

    在函数中,我希望生成范围内的数字列表: (此函数在执行程序时仅调用一次。)

    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”不工作?

    1 回复  |  直到 12 年前
        1
  •  6
  •   Halfdane    12 年前

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

    推荐文章