About std::rand, std::time, std::srand and std::experimental::randint
include <ctime> and uses current time as seed for random generator) as parameter and seeds pseudo-random number generator used by
std::rand() that by its instead returns a pseudo-random integral value between 0 and
RAND_MAX, to know its value just print it, example:
Random numbers are generated at runtime, that is, each time it is executed or each time you call a function with generated value from
std::rand() the numbers will be different unless you remove the line:
std::srand(std::time(nullptr)); or, in the case of the function, if using static.
If you also want numbers without signs, just make a casting, example:
std::srand(static_cast<unsigned>(time(nullptr))), a little useless, but just to inform.
Nice to know that we can limit the size of the random number as in the example we used:
std::rand() % 60, that is, it prints at most up to 60, but if we wanted a range between: 40 and 60, for example?
Of course we could create a condition and add or subtract according to the result value dynamically.
But that’s quite a bit of work, so comes the
std::experimental::randint task. To use it we need to include the
<experimental/random> header, example:
If you think the name gets too long, try summarizing, eg:
namespace rd = std::experimental; and implement:
Alternatively you can use
std::srand with ZERO time:
std::srand(time(0)); or even without scope resolution:
rand() % num;, for example: