To use rand_r
with std::random_shuffle
, you'll need to write a (fairly trivial) wrapper. The random number generator you pass to random_shuffle
needs to accept a parameter that specifies the range of numbers to be produced, which rand_r
does not.
Your wrapper would look something like this:
class rand_x {
unsigned int seed;
public:
rand_x(int init) : seed(init) {}
int operator()(int limit) {
int divisor = RAND_MAX/(limit+1);
int retval;
do {
retval = rand_r(&seed) / divisor;
} while (retval > limit);
return retval;
}
};
You'd use it with random_shuffle
something like:
std::random_shuffle(whatever.begin(), whatever.end(), rand_x(some_seed));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…