3

除了是个垃圾程序员之外,我的行话还不够格。我会尽力解释我自己。我已经使用randomlib实现了一个 Merssene twister 随机数生成器。诚然,我对 Visual 8 C++ 的随机数生成器的工作原理不太熟悉,但我发现我可以在其中播种一次srand(time(NULL))main()并且可以安全地rand()在其他类中使用。我拥有的 Merssene twister 需要创建一个对象,然后为该对象播种。

#include <RandomLib/Random.hpp>
RandomLib::Random r;        // create random number object
r.Reseed();                 // seed with a "unique" seed
float d = r.FloatN();   // a random in [0,1] rounded to the nearest double

如果我想在一个类中生成一个随机数,我该如何做到这一点而不必每次都定义一个对象。我只是担心如果我使用计算机时钟,我每次运行都会使用相同的种子(每秒只会改变一次)。

我解释得对吗?

提前致谢

4

1 回答 1

1

Random 对象本质上是您需要保留的状态信息。您可以使用所有常规技术:您可以将其作为全局变量或将其作为参数传递。如果特定类需要随机数,您可以将Random对象保留为类成员,以为该类提供随机性。


C++<random>库的相似之处在于它需要构建一个对象作为随机性/RNG 状态的来源。这是一个很好的设计,因为它允许程序控制对状态的访问,例如,保证多线程的良好行为。C++<random>库甚至包括 mersenne twister 算法。

这是一个示例,显示将 RNG 状态保存为类成员(使用std::mt19937代替Random

#include <random> // for mt19937
#include <algorithm> // for std::shuffle
#include <vector>

struct Deck {
    std::vector<Cards> m_cards;
    std::mt19937 eng; // save RNG state as class member so we don't have to keep creating one

    void shuffle() {
        std::shuffle(std::begin(m_cards), std::end(m_cards), eng);
    }
};

int main() {
    Deck d;
    d.shuffle();
    d.shuffle(); // this reuses the RNG state as it was at the end of the first shuffle, no reseeding
}
于 2012-10-31T19:26:21.957 回答