What is the best way to generate random numbers in C++?

You should use <random>:

#include <random>

typedef std::mt19937 rng_type;
std::uniform_int_distribution<rng_type::result_type> udist(0, 7);

rng_type rng;

int main()
{
  // seed rng first:
  rng_type::result_type const seedval = get_seed(); // get this from somewhere
  rng.seed(seedval);

  rng_type::result_type random_number = udist(rng);

  return random_number;
}

Pre C++11 you could find this either in TR1 (<tr1/random>, std::tr1::mt19937 etc.), or in Boost.random, with essentially the same interface (though there are minor differences).

Leave a Comment