C++11 random numbers

前端 未结 3 1082
夕颜
夕颜 2020-12-05 07:29

I need to generate random numbers, but from as wide a range as possible (64 bit at least). I don\'t care if the distribution is perfect, so std::rand() would wo

3条回答
  •  Happy的楠姐
    2020-12-05 08:18

    We could easily wrap a random number generator engine into srand/rand-like methods like this:

    #include 
    #include 
    
    struct MT19937 {
    private:
        static std::mt19937_64 rng;
    public:
        // This is equivalent to srand().
        static void seed(uint64_t new_seed = std::mt19937_64::default_seed) {
            rng.seed(new_seed);
        }
    
        // This is equivalent to rand().
        static uint64_t get() {
            return rng();
        }
    };
    
    std::mt19937_64 MT19937::rng;
    
    
    int main() {
        MT19937::seed(/*put your seed here*/);
    
        for (int i = 0; i < 10; ++ i)
            std::cout << MT19937::get() << std::endl;
    }
    

    (Like srand and rand, this implementation does not care about thread-safety.)

    Well the wrapper functions are so trivial that you could just use the engine directly.

    #include 
    #include 
    
    static std::mt19937_64 rng;
    
    int main() {
        rng.seed(/*put your seed here*/);
    
        for (int i = 0; i < 10; ++ i)
            std::cout << rng() << std::endl;
    }
    

提交回复
热议问题