在 C++11 之前,我使用 rand()
来自 <cstdlib>
选择在 main()
中播种(或不播种)生成器非常简单函数(例如),然后在 libraryA 中使用由 libraryB 中某个函数生成的随机数。代码如下所示:
LibraryB(生成随机数,老式的方式):
#include <cstdlib> // rand, RAND_MAX
double GetRandDoubleBetween0And1() {
return ((double)rand()) / ((double)RAND_MAX);
}
主程序:
#include <cstdlib> // srand
#include <ctime> // time, clock
int main() {
bool iWantToSeed = true; // or false,
// decide HERE, applies everywhere!
if(iWantToSeed){
srand((unsigned)time(0) + (unsigned int)clock());
}
// (...)
}
LibraryA(使用 LibraryB 中的随机数,根据 main()
中给出的种子生成):
#include "../folderOfLibraryB/Utils_random.h" // GetRandDoubleBetween0And1
void UseSomeRandomness(){
for(int i = 0; i < 1000000; i++){
double nb = GetRandDoubleBetween0And1();
// (...)
}
}
很简单,对吧?
现在我想更新GetRandDoubleBetween0And1()
使用通过 #include <random>
提供的 C++11 标准.我已经阅读并看过示例 here和 there ,但我不知道如何使其适应我的三个模块。当然,在里面播种引擎 GetRandDoubleBetween0And1()
不是正确的做法...
你认为我必须通过 main()
的种子引擎吗?至 UseSomeRandomness()
在 LibraryA 中,然后来自 UseSomeRandomness()
至 GetRandDoubleBetween0And1()
在图书馆B?或者有更简单的方法吗?
最佳答案
Do you think I will have to pass the seeded engine from main() to UseSomeRandomness() in LibraryA, then from UseSomeRandomness() to GetRandDoubleBetween0And1() in LibraryB?
是的。
您将生成器实例化一次,然后将指向它的引用或指针传递到要使用它的任何上下文中。
这就像处理任何其他资源一样。
关于c++ - C++11 : is there a simple way to seed the generator in one place of the code, 中的随机数然后在不同的函数中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44872676/