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

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

}

结果是这样的:

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

关于c++ - std::random_shuffle 产生相同的结果,即使 srand(time(0)) 被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22496942/

相关文章:

c++ - 大型二维静态数组和 vector 的 vector 的内存使用

C++ 如何将 char 数组转换为字节 vector (vector<byte>)

c++ - 如何从函数返回数组并循环遍历它?

c++ - Qt MySQL 查询 - 无法绑定(bind)值

php - 使用 PHP 和 mysqli 从数据库中排除以前的值

random - random() 似乎不会绘制范围极值

C++:在类构造函数中初始化chars数组和int

c++ - 使用 AWS C++ SDK 的基本程序无法编译

java - 球的随机开始位置,避免碰撞

r - 矢量的圆位移距离 n