How to get current seed from C++ rand()?

前端 未结 8 676
名媛妹妹
名媛妹妹 2020-12-31 01:49

I generate a few thousand object in my program based on the C++ rand() function. Keeping them in the memory would be exhaustive. Is there a way to copy the CURRENT

相关标签:
8条回答
  • 2020-12-31 02:21

    rand() does not offer any way to extract or duplicate the seed. The best you can do is store the initial value of the seed when you set it with srand(), and then reconstruct the whole sequence from that.

    The Posix function rand_r() gives you control of the seed.

    The C++11 library includes a random number library based on sequence-generating "engines"; these engines are copyable, and allow their state to be extracted and restored with << and >> operators, so that you can capture the state of a sequence at any time. Very similar libraries are available in TR1 and Boost, if you can't use C++11 yet.

    0 讨论(0)
  • 2020-12-31 02:28

    I would recommend you to use the Mersenne Twister Pseudo-Random Number Generator. It is fast and offer very good random numbers. You can seed the generator in the constructor of the class very simply by

    unsigned long rSeed = 10;
    MTRand myRandGen(rSeed);
    

    Then you just need to store somewhere the seeds you used to generate the sequences...

    0 讨论(0)
提交回复
热议问题