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

前端 未结 8 765
名媛妹妹
名媛妹妹 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:18

    There's no standard way to obtain the current seed (you can only set it via srand), but you can reimplement rand() (which is usually a linear congruential generator) by yourself in a few lines of code:

    class LCG
    {
    private:
        unsigned long next = 1;
    public:
    
        LCG(unsigned long seed) : next(seed) {}
    
        const unsigned long rand_max = 32767
    
        int rand()
        {
            next = next * 1103515245 + 12345;
            return (unsigned int)(next/65536) % 32768;
        }
    
        void reseed(unsigned long seed)
        {
            next = seed;
        }
    
        unsigned long getseed()
        {
            return next;
        }
    };
    

提交回复
热议问题