如何在 C++ 中生成随机数使用<随机>标题成员?随机>
我学会了用 C# 编程,并开始学习 C++。我正在使用 Visual Studio 2010 IDE。我正在尝试使用
中提供的分布类生成随机数。例如,我尝试执行以下操作:
#include <random>
std::normal_distribution<double> *normal = new normal_distribution<double>(0.0, 0.0);
std::knuth_b *engine = new knuth_b();
std::variate_generator<knuth_b, normal_distribution<double>> *rnd;
rnd = new variate_generator<knuth_b, normal_distribution<double>>(engine, normal);
最后一行给出编译器错误: IntelliSense:构造函数“std::tr1::variate_generator<_Engine, _Distrib>::variate_generator [with _Engine=std::tr1::knuth_b, _Distrib=std::tr1::normal_distribution]”没有实例与参数列表
匹配我觉得争论没问题,我做错了什么?当实例化这里的variate_generator类时,你调用哪个方法来获取下一个随机数,即.NET的System.Random.Next()?
I learned to program in C# and have started to learn C++. I'm using the Visual Studio 2010 IDE. I am trying to generate random numbers with the distribution classes available in <random>
. For example I tried doing the following:
#include <random>
std::normal_distribution<double> *normal = new normal_distribution<double>(0.0, 0.0);
std::knuth_b *engine = new knuth_b();
std::variate_generator<knuth_b, normal_distribution<double>> *rnd;
rnd = new variate_generator<knuth_b, normal_distribution<double>>(engine, normal);
The last line gives a compiler error:
IntelliSense: no instance of constructor "std::tr1::variate_generator<_Engine, _Distrib>::variate_generator [with _Engine=std::tr1::knuth_b, _Distrib=std::tr1::normal_distribution]" matches the argument list
My arguments look ok to me, what am I doing wrong? When the variate_generator class here is instantiated, which method do you call to get the next random number i.e. .NET's System.Random.Next()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++0x 中没有 variate_generator,但 std::bind 也可以工作。以下代码在 GCC 4.5.2 和 MSVC 2010 Express 中编译并运行:
PS:尽可能避免
new
。There is no variate_generator in C++0x, but std::bind works just as well. The following compiles and runs in GCC 4.5.2 and MSVC 2010 Express:
PS: avoid
new
when you can.警告:请注意,上述解决方案绑定了引擎的副本,而不是对引擎的引用。因此,如果您也这样做:
std::function rnd2 = std::bind(正常,引擎);
那么rnd对象和rnd2对象将产生完全相同的随机数序列。
ALERT: Note that the above solution binds a copy of the engine, not a reference to the engine. Thus, if you also do:
std::function rnd2 = std::bind(normal, engine);
then the rnd object and the rnd2 object will produce the exact same sequence of random numbers.