Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to generate random numbers in C++11

📅 2014-Aug-27 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

C++11 makes it easier to write simple random number generation code. This was quite a bit convoluted in C++03 as explained in this older post. With some new classes and syntactic sugar, C++11 is much easier.

Here is an example which generates 10 random int8_t and float values:

#include <iostream>
#include <limits>
#include <random>

int main()
{
    std::default_random_engine eng((std::random_device())());
    std::uniform_int_distribution<int8_t> idis(0, std::numeric_limits<int8_t>::max());

    for (int i = 0; i < 10; ++i)
    {
        int8_t v = idis(eng);
        std::cout << (int32_t) v << std::endl;
    }

    std::uniform_real_distribution<float> fdis(0, 2.0);

    for (int i = 0; i < 10; ++i)
    {
        float v = fdis(eng);
        std::cout << v << std::endl;
    }

    return 0;
}