I'd be curious to know if there is a default random boolean generator in the random C++11 library. I've been using a int generator returning 0 or 1 and then converting to bool but I'm trying to optimize my code and thinking that I could save by using from the beginning a bool generator, if it exists.
Asked
Active
Viewed 1,925 times
6
Timothy Shields
- 70,640
- 17
- 114
- 164
Learning is a mess
- 5,905
- 5
- 30
- 64
-
See [this answer](http://stackoverflow.com/a/20527389/1708801) or [this answer](http://stackoverflow.com/a/20646741/1708801) for an example. – Shafik Yaghmour Jun 25 '14 at 19:46
1 Answers
12
See std::bernoulli_distribution in the <random> header, aptly named after the Bernoulli distribution.
std::random_device device;
std::mt19937 gen(device());
std::bernoulli_distribution coin_flip(0.5);
bool outcome = coin_flip(gen);
Timothy Shields
- 70,640
- 17
- 114
- 164