Making A Random Number Generator Random Number Generator Rand.Gen.

    • distribution objects produce random numbers
    • uniform random bit engine objects act as sources of randomness
    #include <random>
    random_engine_type engine;
    distribution_type distribution {parameters,…};
    auto random_value = distribution(engine);

    How to make a single random generator object that ties both a distribution object and an engine object together?

    Lambda Generator Lambda

    • initialize engine & distribution in lambda capture
    • important: lambda must be marked mutable because internal state of engine and distribution need to change with each call
    #include <random>
    auto coin_flip = [
      // init-capture engine + distribution:
      urbg = std::mt19937{},
      distr = std::bernoulli_distribution{0.5}
    ]() mutable -> bool { return distr(urbg); };
    // use generator:
    bool coin = coin_flip();
    
    auto roll = [ urbg = std::mt19937{}, distr = std::uniform_int_distribution<int>{1,6} ]() mutable -> int { return distr(urbg); }; int num = roll();

    Custom Generator Class Custom Class

    if more control over parameters is needed

    #include <random>
    class DiceRoll {
      // engine + distribution as members:
      std::mt19937 urbg_;
      std::uniform_int_distribution<int> distr_;
    public:
      // constructor:
      explicit 
      DiceRoll(int sides) noexcept:     urbg_{}, distr_{1,sides} {}
      // call operator:
      int operator () () noexcept {     return distr_(urbg_); }
    };
    DiceRoll roll_d20{20};
    cout << roll_d20() << '\n';