Just plop the following into a header file, I called mine "random_toolkit.hpp," include it whenever you need random numbers, and you will not need to remember how to set up a C++ RNG:
/* A simple toolkit to help beginners using <random> library an easier task */
// shamelessly stolen and adapted from a C++ working paper: WG21 N3551
// http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3551.pdf
#ifndef __RANDOM_TOOLKIT_HPP__
#define __RANDOM_TOOLKIT_HPP__
#include <random>
#include <chrono>
namespace rtk
{
inline std::default_random_engine& urng()
{
static std::default_random_engine URNG { };
return URNG;
}
inlinevoid srand()
{
staticunsigned seed = static_cast<unsigned> (std::chrono::system_clock::now().time_since_epoch().count());
staticbool seeded = false;
if (!seeded)
{
urng().seed(seed);
seeded = true;
}
}
inlinevoid srand(unsigned seed)
{
staticbool seeded = false;
if (!seeded)
{
urng().seed(seed);
seeded = true;
}
}
// two function overloads to obtain uniform distribution ints and doubles
inlineint rand(int from, int to)
{
static std::uniform_int_distribution<> dist { };
return dist(urng(), decltype(dist)::param_type { from, to });
}
inlinedouble rand(double from, double to)
{
static std::uniform_real_distribution<> dist { };
return dist(urng(), decltype(dist)::param_type { from, to });
}
// function for rolling dice, and checking if the # of pips is nonstandard
inlineint roll_die(int pips)
{
//check to see if the number of die pips is less than 2
if (pips < 2)
{
return 0;
}
return rand(1, pips);
}
}
#endif
Then you can mash together code almost as easily as using the C library srand/rand functions: