我正在尝试对字母表的随机排列进行一些处理,但是尽管使用了 srand(myseed),但每个排列都会产生相同的结果
我已经包含了 <algorithm>
header 。
string create_permutation(unsigned seed)
{
srand(seed);
string permutation = ALPHABET;
random_shuffle(permutation.begin(), permutation.end());
return permutation;
}
cout << create_permutation(2) << endl; // or 3, 4, 5 etc
// continuously returns 'XQACKHSLOJ,TRBZNGV.W FIUEYDMP
如有任何帮助,我们将不胜感激。
编辑:最小、完整且可验证的示例
编辑 2: 对 mcve 的调整
#include <iostream>
#include <algorithm>
using namespace std;
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,' ";
string create_permutation(unsigned seed)
{
srand(seed);
string permutation = ALPHABET;
random_shuffle(permutation.begin(), permutation.end());
return permutation;
}
int main(){
cout << create_permutation(2) << endl; // or 3, 4, 5 etc
// continuously returns 'XQACKHSLOJ,TRBZNGV.W FIUEYDMP
return 0;
}
最佳答案
问题
- 洗牌不是随机的,因为
shuffle_random
每次调用时都为随机数生成器使用相同的种子。
srand
不播种 random_shuffle
功能,它播种rand
和 random_shuffle
通常调用rand
,但不必。
random_shuffle
有两种形式:
一个接受 2 个参数(开始/结束迭代器)
一个需要 3 个(开始/结束迭代器和一个随机生成器)。
您已经证明您知道如何使用第一种形式,但第一种形式的问题在于它在不同平台和不同编译器上的实现方式不同。它可能不会使用 rand()
根本就是srand
的功能种子。
您应该使用 3 参数形式并提供随机数生成器作为函数的参数。
可以关注this detailed answer了解如何制作您自己的随机数生成器,或者您可以提供 rand()
到 random_shuffle
作为随机数生成器。
关于c++ - random_shuffle 和 srand() 每次都给我相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36725218/