【发布时间】:2014-09-03 12:34:06
【问题描述】:
我正在尝试将新的 c++ <random> 标头与全局固定种子一起使用。这是我的第一个玩具示例:
#include <iostream>
#include <random>
int morerandom(const int seednum,const int nmax){
std::mt19937 mt;
mt.seed(seednum);
std::uniform_int_distribution<uint32_t> uint(0,nmax);
return(uint(mt));
}
int main(){
const int seed=3;
for (unsigned k=0; k<5; k++){
std::cout << morerandom(seed,10) << std::endl;
}
return 0;
}
所以问题是:如何修复 main() 中的种子并从
morerandom()?
换句话说,我需要经常调用morerandom()(k 会很大),但这些随机数应该始终使用相同的seed 绘制。我想知道定义整个块是否可能/更有效:
std::mt19937 mt;
mt.seed(seednum);
在 main 中,只需将 mt 传递给 morerandom()。我试过了:
#include <iostream>
#include <random>
int morerandom(const int nmax)
{
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) << std::endl;
}
return 0;
}
但编译器抱怨:
error: ‘mt’ was not declared in this scope return(uint(mt));
【问题讨论】:
-
编译器的抱怨是正确的,因为
mt的名称在morerandom内部是未知的。请明确你想要做什么。我真的不明白你在做什么。 -
@filmore:我不知道如何将 mt 传递给函数(到处搜索却找不到!)