Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Random Number Generation Using

📅 2010-Nov-24 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

Note: Please note that the random header has undergone substantial change for C++11 and later. This post is outdated and only meant for older versions of C++. For the latest, please refer to this page.

C++ can get very irritating if all you want is a simple solution. Take random number generation for example. The header was added to C++ to provide all kinds of random number generation. While it does cover any kind of random generation you can dream of, it makes writing a simple random generator super-hard! Unlike C or C#, where you can quickly generate random numbers with little code, in C++ it takes a lot of reading, pondering and lots of ugly-looking code.

The header file provides many kinds of classes:

Simple Random Number Generation

Here is a simple random number generator that produces random float values. It uses the variate_generator to wrap a minstd_rand engine and uniform_real_distribution.

#include <random>
using namespace std;

typedef minstd_rand                             Engine;
typedef uniform_real_distribution<float>        Distribution;
typedef variate_generator<Engine, Distribution> Generator;

Generator gen( Engine(9999), Distribution( 10, 100 ) );

cout << "Random value: " << gen() << endl;

The minstd_rand engine requires a seed, here we seed it with 9999. We also provide the uniform_real_distribution an output range of [10.0,100.0).

Simple Random Generator Class

If all I want is to generate some random number simply and quickly, the C++ looks truly foreboding! ☹

Here is a simple random number generator class that wraps up the complexity to provide a simple interface:

#include <random>
using namespace std;

class MyRandom
{
private:
    // Types
    typedef minstd_rand                             Engine;
    typedef uniform_real_distribution<float>        Distribution;
    typedef variate_generator<Engine, Distribution> Generator;

    // To hold the generator
    Generator* _gen;

public:
    MyRandom( int seed, float minVal, float maxVal )
    {
        _gen = new Generator( Engine( seed ), Distribution( minVal, maxVal ) );
    }

    ~MyRandom()
    {
        delete _gen;
    }

    float next()
    {
        return (*_gen)();
    }
};

The above class interface is influenced by C# Random, which is how simple and accessible C++ should have been! Writing code using the above class is easy:

const int seed      = 9999;
const float minVal  = 10;
const float maxVal  = 100;
MyRandom myRand( seed, minVal, maxVal );
cout << "Random value: " << myRand.next() << endl;

I hope this post made digesting a wee bit easier! 😊