samedi 3 octobre 2015

How to use

C++11 introduced the header <random> with declarations for random number engines and random distributions. That's great - time to replace those uses of rand() which is often problematic in various ways. However, it seems far from obvious how to replace

srand(n);
// ...
int r = rand();

Based on the declarations it seems a uniform distribution can be built something like this:

std::default_random_engine engine;
engine.seed(n);
std::uniform_int_distribution<> distribution;
auto rand = [&](){ return distribution(engine); }

This approach seems rather involved and is surely something I won't remember unlike the use of srand() and rand(). I'm aware of N4531 but even that still seems to be quite involved.

Is there a reasonably simple way to replace srand() and rand()?




Aucun commentaire:

Enregistrer un commentaire