尝试用C ++ 11替换旧的随机API

问题描述 投票:1回答:1

我有一段使用随机数的现有代码:

double Foo(bool b)
{
    double d = 200.0;
    if (b)
    {
        d /= RAND_MAX + 1;
        srand((unsigned)time(NULL));
    }
    return (d / rand());
}

我想用C ++ 11替代它,但以前从未使用过该API。经过this examplethis document之后,我想到了以下代码:

#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()));
    }
};

[我正在使用Visual Studio2019。在Ideone上尝试MVCE类时,它可以工作,但是Visual Studio抱怨m_generator.max()' and m_ge​​nerator.min()'并出现以下错误:

E0133 expected a member name

[悬停在max()上时显示max宏(#define max(a, b) (((a) > (b)) ? (a) : (b))),而悬停在min()上则显示min宏(#define min(a, b) (((a) < (b)) ? (a) : (b))

自从我第一次使用新API以来,有人可以验证我是否正确使用了它吗?有人可以帮助我删除提到的错误吗?

c++ c++11 random
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.