I'm just starting to use C++11's <random>
header for the first time, but there are still some things that seem a bit mysterious. This question is about the intended, idiomatic, best-practice way to accomplish a very simple task.
Currently, in one part of my code I have something like this:
std::default_random_engine eng {std::random_device{}()};
std::uniform_int_distribution<> random_up_to_A {0, A};
std::uniform_int_distribution<> random_up_to_B {0, B};
std::uniform_int_distribution<> random_up_to_some_other_constant {0, some_other_constant};
and then when I want an integer between 0 and B I call random_up_to_B(eng)
.
Since this is starting to look a bit silly, I want to implement a function rnd
such that rnd(n, eng)
returns a random integer between 0 and n.
Something like the following ought to work
template <class URNG>
int rnd(int n, URNG &eng) {
std::uniform_int_distribution<> dist {0, n};
return dist(eng);
}
but that involves creating a new distribution object every time, and I get the impression that's not the way you're supposed to do it.
So my question is, what is the intended, best-practice way to accomplish this simple task, using the abstractions provided by the <random>
header? I ask because I'm bound to want to do much more complicated things than this later on, and I want to make sure I'm using this system in the right way.