random_shuffle并不是真的随机
random_shuffle not really random
我在这样的向量上使用random_shuffle
:
#include <algorithm>
vector <Card> deck;
//some code to add cards to the deck here
random_shuffle ( deck.begin(), deck.end() );
运行时,甲板的内容是混合的,但是当我重新启动程序时,会保留这种混淆的顺序。
我错过了什么吗?如何使其真正随机?
您需要先使用 srand 播种伪随机数生成器。
#include <algorithm>
#include <cstdlib>
...
std::srand(std::time(0));
vector <Card> deck;
//some code to add cards to the deck here
random_shuffle ( deck.begin(), deck.end() );
上面链接中的注释:
一般来说,伪随机数生成器应该只 在调用 rand() 之前播种一次,然后程序开始。 它不应该重复播种,或者每次你都愿意时重新播种 生成一批新的伪随机数。
使用当前C++(即 C++11),您可以使用 shuffle
算法,该算法可以将伪随机数生成器 (PRNG) 对象(您可以播种)作为第三个参数:
#include <iostream>
#include <random>
#include <algorithm>
#include <vector>
#include <string>
#include <ctime>
using namespace std;
int main(int argc, char **argv)
{
vector<string> v;
for (int i = 1; i<argc; ++i)
v.push_back(argv[i]);
mt19937 g(static_cast<uint32_t>(time(0)));
shuffle(v.begin(), v.end(), g);
for (auto &x : v)
cout << x << ' ';
cout << 'n';
}
(对于GCC 4.8.2,您需要通过g++ -std=c++11 -Wall -g shuffle.cc -o shuffle
编译它)
在上面的示例中,PRNG 是使用当前系统时间设定种子的。
对于 C++11 之前的编译器,STL 中只有 random_shuffle
算法 - 但即使这样,您也可以选择为其指定数字生成器对象/函数。请注意,您不能像 mtl19937
一样将 PRNG 对象插入其中(因为它不提供operator()(U upper_bound)
成员)。
因此,您可以像这样提供自己的适配器:
#include <iostream>
#include <random>
#include <algorithm>
#include <vector>
#include <string>
#include <ctime>
using namespace std;
struct Gen {
mt19937 g;
Gen()
: g(static_cast<uint32_t>(time(0)))
{
}
size_t operator()(size_t n)
{
std::uniform_int_distribution<size_t> d(0, n ? n-1 : 0);
return d(g);
}
};
int main(int argc, char **argv)
{
vector<string> v;
for (int i = 1; i<argc; ++i)
v.push_back(argv[i]);
random_shuffle(v.begin(), v.end(), Gen());
for (vector<string>::const_iterator i = v.begin(); i != v.end(); ++i)
cout << *i << ' ';
cout << 'n';
}
放置行:
srand (time (0));
在执行任何其他操作之前,例如在 main()
的开头。
如果没有它,将始终使用默认种子 1,从而导致来自 rand()
和使用它的任何内容的相同序列。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- 循环中的随机函数
- 在c++构造函数中使用随机字符串生成器
- 在决定是通过参考还是通过价值时,尺寸真的是一个问题吗
- 使用std::mt19937从字符串中返回一个随机单词
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 如何在C++中高效地构造随机骰子
- 在类中使用随机生成器时出现性能问题
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 将字符随机转换为大写的函数
- 字节真的是最小可寻址单元吗
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 如何在 std::vector 中找到<bool>哪些索引是真的?
- 如何生成一个随机的 n 位数,其中 n 是任意的
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- std::string 的对象真的可以移动吗?
- random_shuffle并不是真的随机