【发布时间】:2016-06-13 03:51:26
【问题描述】:
我需要一些随机数来进行模拟,并且正在使用来自 nuwen.net 的 MinGW Distro 来试验 C++ 11 随机库。
正如在其他几个线程中讨论的那样,例如Why do I get the same sequence for every run with std::random_device with mingw gcc4.8.1?,random_device 不生成随机种子,即下面的代码,用 GCC 编译,每次运行都会生成相同的数字序列。
// test4.cpp
// MinGW Distro - nuwen.net
// Compile with g++ -Wall -std=c++14 test4.cpp -o test4
#include <iostream>
#include <random>
using namespace std;
int main(){
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dist(0,99);
for (int i = 0; i< 16; ++i){
cout<<dist(mt)<<" ";
}
cout <<endl;
}
运行 1:56 72 34 91 0 59 87 51 95 97 16 66 31 52 70 78
运行 2:56 72 34 91 0 59 87 51 95 97 16 66 31 52 70 78
为了解决这个问题,建议使用 boost 库,然后代码将如下所示,采用 How do I use boost::random_device to generate a cryptographically secure 64 bit integer? 和 A way change the seed of boost::random in every different program run,
// test5.cpp
// MinGW Distro - nuwen.net
// Compile with g++ -Wall -std=c++14 test5.cpp -o test5
#include <boost/random.hpp>
#include <boost/random/random_device.hpp>
#include <iostream>
#include <random>
using namespace std;
int main(){
boost::random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dist(0,99);
for (int i = 0; i< 16; ++i){
cout<<dist(mt)<<" ";
}
cout <<endl;
}
但此代码无法编译,给出错误“未定义对‘boost::random::random_device::random_device() 的引用”。请注意,包含目录中的 random.hpp 和 radndom_device.hpp 都可用。谁能建议代码或编译有什么问题?
【问题讨论】:
-
boost::random 是一个编译好的boost库,在你的命令行中你必须链接它来编译这个程序,否则你会得到一个链接器错误。
-
好的,用g++编译上面的test5.cpp -std=c++14 test5.cpp -o test5 E:\MinGW\lib\libboost_random.a E:\MinGW\lib\libboost_system.a有效,即为每次运行生成一个不同随机数的列表。
标签: c++11 boost random mingw random-seed