Using boost::random and getting same sequence of numbers

前端 未结 6 708
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 19:04

I have the following code:

Class B {

void generator()
{
    // creating random number generator
    boost::mt19937 randgen(static_cast(s         


        
6条回答
  •  暖寄归人
    2020-12-19 19:54

    With Boost.Random you can save the state of the random number generator--for example, you can save it to a text file. This is done with streams.

    For example, using your code, after you seed the generator and have run it once, you can save the state with an output stream, like so:

    std::ofstream generator_state_file("rng.saved");
    generator_state_file << randgen;
    

    Then later, when you've created a new generator, you can load the state back from that file using the opposite stream:

    std::ifstream generator_state_file("rng.saved");
    generator_state_file >> randgen;
    

    And then use the state to generate some more random numbers, and then re-save the state, and so on and so on.

    It may also be possible to save the state to a std::string using std::stringstream, if you don't want to use a file, but I haven't personally tried this.

提交回复
热议问题