How to generate random numbers in C++11

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;
}

view raw
randgen.cpp
hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.