我正在尝试使用新的c++ <random>标头与全局固定种子一起使用。这是我的第一个玩具示例:
#include <iostream>\n#include <random>\nint morerandom(const int seednum,const int nmax){\n std::mt19937 mt;\n mt.seed(seednum);\n std::uniform_int_distribution<uint32_t> uint(0,nmax);\n return(uint(mt));\n}\nint main(){\n const int seed=3;\n for (unsigned k=0; k<5; k++){\n std::cout << morerandom(seed,10) << std::endl;\n }\n return 0;\n} \nRun Code Online (Sandbox Code Playgroud)\n\n所以问题是:如何修复 中的种子main()并从 \n 中获得可重现的输出morerandom()?
换句话说,我需要调用morerandom()很多(k会很大),但这些随机数应该始终使用相同的值来绘制seed. 我想知道定义整个块是否可能/更有效:
std::mt19937 mt;\nmt.seed(seednum);\nRun Code Online (Sandbox Code Playgroud)\n\n在 main 内部并传递mt给morerandom(). 我尝试过:
#include <iostream>\n#include <random>\nint morerandom(const int nmax)\n{\n\n std::uniform_int_distribution<uint32_t> uint(0,nmax);\n return(uint(mt));\n}\n\n\nint main()\n{\n const int seed=3;\n std::mt19937 mt;\n mt.seed(seed);\n for (unsigned k=0; k<5; k++)\n {\n\n std::cout << morerandom(10) << std::endl;\n }\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n但编译器抱怨:
\n\nerror: \xe2\x80\x98mt\xe2\x80\x99 was not declared in this scope return(uint(mt));\nRun Code Online (Sandbox Code Playgroud)\n
解决方案1
#include <iostream>
#include <random>
int morerandom(const int nmax, std::mt19937& mt)
// ^^^^^^^^^^^^^^^^
{
std::uniform_int_distribution<uint32_t> uint(0,nmax);
return(uint(mt));
}
int main()
{
const int seed=3;
std::mt19937 mt;
mt.seed(seed);
for (unsigned k=0; k<5; k++)
{
std::cout << morerandom(10, mt) << std::endl;
// ^^
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
解决方案2
#include <iostream>
#include <random>
std::mt19937 mt;
// ^^^^^^^^^^^^^
int morerandom(const int nmax)
{
std::uniform_int_distribution<uint32_t> uint(0,nmax);
return(uint(mt));
}
int main()
{
const int seed=3;
mt.seed(seed);
for (unsigned k=0; k<5; k++)
{
std::cout << morerandom(10) << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1938 次 |
| 最近记录: |