I am running C ++ Primer, and I just finished the section on utilities <random>. A few questions ask me a question:
Exercise 17.28: Write a function that generates and returns a uniformly distributed random unsigned int each time it is called.
Exercise 17.29. Allow the user to provide the seed as an optional argument to the function that you wrote in the previous exercise.
Exercise 17.30: Repeat this function this time to take the minimum and maximum value for the numbers returned by the function.
These questions want me to use the classes discussed random_default_engineand uniform_int_distribution. The first question is quite simple:
#include <random>
unsigned randomUns(){
static default_random_engine e;
static uniform_int_distribution<unsigned> u;
return u(e);
}
, static, , , . , :
unsigned randomUns(unsigned minV, unsigned maxV, default_random_engine::result_type seed = 0){
static default_random_engine e(seed);
static uniform_int_distribution<unsigned> u(minV, maxV);
return u(e);
}
, , , . , u randomUns, . . .
cout << randomUns(2,3) << " " << randomUns(5,6);
2 3, , .
seed. ? / :
static default_random_engine::result prev = 0;
static default_random_engine e(seed);
if(prev != seed){
e.seed(seed)
prev = seed;
}
, , .
randomUns(1,2,50);
randomUns(1,2,60);
randomUns(1,2,50);
, , , reset . .
, - static . , /, .
, random_default_engine uniform_int_distribution?