C ++ equivalent of new Random (seed) in C #

When we use a random number generator in C #, we can define a variable of type

private Random _rndGenerator; 

in class and then call

 _rndGenerator = new Random(seed); 

correctly in the class constructor.

My question is:

What is the C ++ equivalent of such a definition (i.e. RNG in a class). I think this is the wrong approach to use.

 srand((unsigned int)seed); 

right?

+6
source share
2 answers

C ++ 11 has much more powerful means of generating random numbers. Here is 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 get seeds. <random> provides potential access to some hardware entropy with the std::random_device , which you can use to seed your PRNGs.

 std::size_t get_seed() { std::random_device entropy; return entropy(); } 
+14
source

C ++ has a built-in global random number generator. If you want to sow it, then srand((unsigned int)seed) is the way to go. This is not exactly the same as the C # code you showed. When you write:

 Random _rndGenerator = new Random(seed); 

You get a separate instance of the random number generator. Thus, you can have several random number generators in your program. As far as I know, the C ++ library does not have this design, although it seems that C ++ 11. does.

In short, srand((unsigned int)seed) true if you are using older versions of C ++ or just want to use one RNG in your program. If you need multiple RNGs, then use C ++ 11, or collapse your own.

+1
source

Source: https://habr.com/ru/post/903133/


All Articles