如何确保 std::random_shuffle 总是产生不同的结果?

2021-12-21 00:00:00 random shuffle c++ std

是否有一些类似于 srand() 的函数,我需要调用它来确保 std::random_shuffle() 总是产生不同的结果?即如果我用相同的数据多次调用它,我希望每次的顺序都不同.我如何确保这一点?

Is there some function, similar to srand(), that I need to call to make sure that std::random_shuffle() always produces different results? i.e. if I call it several times with the same data, I want the order to be different every time. How can I make sure of that?

推荐答案

std::random_shuffle 有两种形式.一个接受 2 个参数(开始/结束迭代器),一个接受 3 个参数(开始/结束迭代器和一个随机生成器).

std::random_shuffle has two forms. One that takes 2 arguments (begin/end iterators), and one that takes 3 (begin/end iterator and a random generator).

第一种形式使用 std::rand(),因此您将使用 std::srand() 为其随机数生成器提供种子.您也可以使用 3 参数版本并自己提供 RNG.

The first form uses std::rand(), so you would use std::srand() to seed it's random number generator. You can also use the 3-argument version and provide the RNG yourself.

相关文章