How to generate a random number in C++?

后端 未结 11 1539
萌比男神i
萌比男神i 2020-11-22 11:14

I\'m trying to make a game with dice, and I need to have random numbers in it (to simulate the sides of the die. I know how to make it between 1 and 6). Using



        
11条回答
  •  天涯浪人
    2020-11-22 12:04

    Can get full Randomer class code for generating random numbers from here!

    If you need random numbers in different parts of the project you can create a separate class Randomer to incapsulate all the random stuff inside it.

    Something like that:

    class Randomer {
        // random seed by default
        std::mt19937 gen_;
        std::uniform_int_distribution dist_;
    
    public:
        /*  ... some convenient ctors ... */ 
    
        Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
            : gen_{seed}, dist_{min, max} {
        }
    
        // if you want predictable numbers
        void SetSeed(unsigned int seed) {
            gen_.seed(seed);
        }
    
        size_t operator()() {
            return dist_(gen_);
        }
    };
    

    Such a class would be handy later on:

    int main() {
        Randomer randomer{0, 10};
        std::cout << randomer() << "\n";
    }
    

    You can check this link as an example how i use such Randomer class to generate random strings. You can also use Randomer if you wish.

提交回复
热议问题