C ++等价的新的随机(种子)在C# [英] C++ equivalent of new Random(seed) in C#
问题描述
当我们在C#中使用随机数生成器时,我们可以定义一个变量,如
private Random _rndGenerator;
然后调用
_rndGenerator = new Random(seed);
$ b p>我的问题是:
这种定义的C ++等价物是什么(即类中的RNG)。我认为这不是一个正确的方法使用
srand((unsigned int)seed);
对吗?
解决方案 C ++ 11具有更强大的随机数生成功能。这里有一个例子:
#include< random>
#include< functional>
std :: size_t get_seed(); //什么是获得种子的首选方式
typedef std :: mt19937 engine_type; // a Mersenne twister engine
std :: uniform_int_distribution< engine_type :: result_type> udist(0,200);
engine_type engine;
int main()
{
// seed rng first:
engine_type :: result_type const seedval = get_seed();
engine.seed(seedval);
//绑定引擎和分发
auto rng = std :: bind(udist,engine);
//生成一个随机数
auto random_number = rng();
return random_number;
}
有很多种获取种子的方法。 < random>
使用 std :: random_device
类提供对某些硬件熵的潜在访问,种子你的PRNG。
std :: size_t get_seed(){
std :: random_device entropy;
return entropy();
}
When we are using a random number generator in C#, we can define a variable like
private Random _rndGenerator;
in a class and then call
_rndGenerator = new Random(seed);
correctly in the constructor of the class.
My question is:
What is a C++ equivalent of such a definition (i.e. an RNG in a class). I think it is not a correct approach to use
srand((unsigned int)seed);
right?
解决方案 C++11 has much more powerful random-number generation facilities. Here's an example:
#include <random>
#include <functional>
std::size_t get_seed(); // whatever is the preferred way of obtaining a seed
typedef std::mt19937 engine_type; // a Mersenne twister engine
std::uniform_int_distribution<engine_type::result_type> udist(0, 200);
engine_type engine;
int main()
{
// seed rng first:
engine_type::result_type const seedval = get_seed();
engine.seed(seedval);
// bind the engine and the distribution
auto rng = std::bind(udist, engine);
// generate a random number
auto random_number = rng();
return random_number;
}
There are many ways to obtain seeds. <random>
provides potential access to some hardware entropy with the std::random_device
class, which you can use to seed your PRNGs.
std::size_t get_seed() {
std::random_device entropy;
return entropy();
}
这篇关于C ++等价的新的随机(种子)在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!