In addition to seeding your random number generator, I would recommend you avoid rand()
entirely, if possible. It's not usually a very good pRNG, and common usages (such as rand() % size
) produce biased results. A better alternative, if available, is the standard C++ <random>
library.
Some benefits of <random>
over rand()
:
- several engines with well defined characteristics to suit different needs.
- predefined distributions, easier to use correctly than to produce your own.
- well specified behavior in threaded programs.
Example:
#include <random>
#include <iostream>
#include <functional>
int main() {
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 e(seed);
int size = 10;
std::uniform_int_distribution d(1,size);
std::cout << d(e) << '\n';
}
You can also bind everything up into a single function object, if that suits your usage better.
#include <functional>
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
auto rand = std::bind(std::uniform_int_distribution<>(1,size),
std::mt19937(seed));
std::cout << rand() << '\n';