Std::random_shuffle即使调用一次srand(time(0))也会产生相同的结果
std::random_shuffle produce the same result even though srand(time(0)) called once
在一个函数中,我想生成一个范围内的数字列表:(这个函数在执行程序时只会被调用一次)
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()
。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 密码登录程序将永远循环并显示不正确的结果
- c++ time(NULL)给出不一致的结果
- Std::random_shuffle即使调用一次srand(time(0))也会产生相同的结果