Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c#

random

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?

like image 481
derekhh Avatar asked Dec 05 '11 18:12

derekhh


1 Answers

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();
}
like image 100
R. Martinho Fernandes Avatar answered Sep 19 '22 23:09

R. Martinho Fernandes