Is it modern C++ to use srand to set random seed?

后端 未结 3 1702
慢半拍i
慢半拍i 2021-02-13 05:07

For code that uses std::random_shuffle, I need to set a random seed so that the pseudorandom sequences produced vary in each program run.

The code example h

3条回答
  •  走了就别回头了
    2021-02-13 05:22

    random_shuffle uses an implementation-defined random number generator unless you provide one. So, no, using srand is not necessarily correct.

    Otherwise it uses the generator you provide. You can use rand if you want to be sure that is what gets used.

    srand(seed);
    std::random_shuffle(first, last, [](int n) { return rand() % n; });
    // this is a biased generator
    // see 
    

    However, I recommend using the new facilities instead of rand(). Example follows.

    std::default_random_engine gen(seed);
    
    std::shuffle(first, last, gen);
    

提交回复
热议问题