默认随机引擎作为类成员,即使通过参考文献未更新外部引擎
我知道我必须通过引用传递随机引擎,以使其从功能中更新。但是,如果我在课堂构造中通过引用将其传递,则看起来种子在班级外面没有变化。
最低限度的工作示例:
#include<iostream>
#include<random>
class rv{
public:
std::default_random_engine rv_eng;
rv(std::default_random_engine & eng){
this->rv_eng = eng;
}
double nd(){
std::normal_distribution<double> ndist {0.0, 1.0};
double draw = ndist(this->rv_eng);
return draw;
}
};
int main(){
std::default_random_engine main_engine;
main_engine.seed(123);
std::cout << main_engine << std::endl;
rv rv_instance(main_engine);
std::cout << rv_instance.nd() << std::endl;
std::cout << main_engine << std::endl;
return 0;
}
我得到的结果是
123
-0.331232
123
,我希望第二个发电机会更改。为什么一样?
I know that I have to pass the random engine by reference in order for it to update out of a function. However, if I pass it by reference in a class construction, it looks like the seed is not changing outside of the class.
Minimum working example:
#include<iostream>
#include<random>
class rv{
public:
std::default_random_engine rv_eng;
rv(std::default_random_engine & eng){
this->rv_eng = eng;
}
double nd(){
std::normal_distribution<double> ndist {0.0, 1.0};
double draw = ndist(this->rv_eng);
return draw;
}
};
int main(){
std::default_random_engine main_engine;
main_engine.seed(123);
std::cout << main_engine << std::endl;
rv rv_instance(main_engine);
std::cout << rv_instance.nd() << std::endl;
std::cout << main_engine << std::endl;
return 0;
}
The result I get is
123
-0.331232
123
While I would have expected the second generator to change. Why is it the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就像其他已经建议的人一样;使用初始化列表,这样您就可以将参考变量作为成员:
Like someone else already suggested; use an initializer list, that way you can have a reference variable as a member: