Professional C__ - Marc Gregoire [285]
mt19937 eng(static_cast uniform_int_distribution auto gen = std::bind(dist, eng); vector generate(vec.begin(), vec.end(), gen); for (auto i : vec) cout << i << " "; Code snippet from Random\generate.cpp Remember that the generate() algorithm overwrites existing elements and will not insert new elements. This means that you first need to size the vector to hold the number of elements you need, and then call the generate() algorithm. The previous example sizes the vector by specifying the size as argument to the constructor. Even though you don’t know the exact type of gen(), because of the use of the auto keyword, it’s still possible to pass gen() to another function that wants to use that generator. However, you cannot use a normal function; you need to use a template function. The previous example can be adapted to do the generation of random numbers in a function called fillVector(), which is a template function that looks as follows: template void fillVector(vector { generate(vec.begin(), vec.end(), rndGen); } Code snippet from Random\generate_function.cpp The previous example can then be adapted as follows: mt19937 eng(static_cast uniform_int_distribution auto gen = std::bind(dist, eng); vector fillVector(vec, gen); for (auto i : vec) cout << i << " "; Code snippet from Random\generate_function.cpp Random Number Distributions A distribution is a mathematical formula describing how numbers are distributed within a certain range. The C++11 random number generator library comes with the following distributions that can be used with pseudo-random number engines to define the distribution of the generated random numbers. It’s a compacted representation. The first line of each distribution is the class name and class template parameters, if any. The next lines are a constructor for the distribution. Only one constructor for each distribution is shown to give you an idea of the class. Consult the Standard Library Reference resource on the website (www.wrox.com) for a detailed list of all constructors and methods of each distribution. Uniform distributions: template uniform_int_distribution(IntType a = 0, IntType b = numeric_limits template uniform_real_distribution(RealType a = 0.0, RealType b = 1.0); Bernoulli distributions: class bernoulli_distribution bernoulli_distribution(double p = 0.5); template binomial_distribution(IntType t = 1, double p = 0.5); template geometric_distribution(double p = 0.5); template negative_binomial_distribution(IntType k = 1, double p = 0.5); Poisson distributions: template poisson_distribution(double mean = 1.0); template