I hope they add some novice-friendly APIs to <random> in a future version. What they have now is powerful, but very hard to use and prone to errors that might be even worse than rand(). Consider this:
#include <iostream>
#include <random>
// Somewhere in the code, a simple function to generate doubles
// between 0 and 10
int f() {
static std::default_random_engine eng(time(0));
static std::uniform_int_distribution<> d(0,10);
return d(eng);
}
// Far far away in another file, another function that does the same thing:
int g() {
static std::default_random_engine eng(time(0));
static std::uniform_int_distribution<> d(0,10);
return d(eng);
}
int main()
{
for (int i=0; i<10; ++i) {
std::cout << f() << ' ' << g() << '\n';
}
}
2 2
1 1
0 0
5 5
3 3
3 3
4 4
1 1
7 7
1 1
Unless time(0) returns different values between the first calls to f() and g(), the two functions generate the exact same sequence. This isn't some fluke. It's by design. This is code that many programmers might write.
Do you really want different engines generating the same sequence? Is this really better than:
#include <iostream>
#include <cstdlib>
// Somewhere in the code, a simple function to generate doubles
// between 0 and 10
int f() {
return rand() % 10;
}
// Far far away in another file, another function that does the same thing:
int g() {
return rand() % 10;
}
int main()
{
srand(time(0));
for (int i=0; i<10; ++i) {
std::cout << f() << ' ' << g() << '\n';
}
}
6 6
4 3
3 1
0 1
3 8
5 7
1 9
6 9
2 0
6 9
Both programs are problematic, but which is worse? I'd argue that the first one is likely to create far bigger problems than the second.
This isn't to say that the <random> facilities are bad, it's just that they are so difficult to use that they can cause bigger problems than they solve. That's why some simplified APIs would be helpful.
I hope they add some novice-friendly APIs to <random> in a future version.
I totally agree. Until the ISO Committee does that I'll continue using my cobbled-up random toolkit I bashed together from that 2013 working paper I linked earlier. It ain't perfect, but it works for me. And if others want to try it let me know.