I have a piece of existing code that uses random numbers:
double Foo(bool b)
{
double d = 200.0;
if (b)
{
d /= RAND_MAX + 1;
srand((unsigned)time(NULL));
}
return (d / rand());
}
I would like to replace it with C++11 equivalent, but have never used that API before. After going through this example and this document I came up with the following code:
#include <chrono>
#include <random>
class MVCE
{
private:
std::default_random_engine m_generator;
std::uniform_int_distribution<int> m_distribution{};
public:
MVCE()
{
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
m_generator.seed(seed);
}
double Foo(bool b)
{
double d = 200.0;
if(b)
{
d /= m_generator.max() - m_generator.min() + 1;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
m_generator.seed(seed);
}
return (d / (m_generator() - m_generator.min()));
}
};
I am using Visual Studio 2019. When trying out MVCE
class on Ideone, it works, but Visual studio complains for m_generator.max()' and
m_generator.min()' with the following error:
E0133 expected a member name
When hovering over max()
it shows the max
macro (#define max(a, b) (((a) > (b)) ? (a) : (b))
), while hovering above min()
shows min
macro (#define min(a, b) (((a) < (b)) ? (a) : (b))
).
Since I use the new API for the first time, can someone verify that I have used it correctly? Can someone help me remove the mentioned error?
Aucun commentaire:
Enregistrer un commentaire