我需要一些随机数进行模拟,并使用nuwen.net中的MinGW Distro使用C++ 11随机库进行试验。MinGW boost random_device编译错误
正如其他几个线程所讨论的,例如, 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;
}
但这个代码不会补偿ile,给出错误“未定义的引用'boost :: random :: random_device :: random_device()”。请注意,random.hpp和radndom_device.hpp都在include目录中可用。任何人都可以提出代码或编译有什么问题吗?
boost :: random是一个编译的boost库,在你的命令行中你必须链接它来编译这个程序,否则你会得到一个链接错误。 –
好的,用g ++ -std = C++编译test5.cpp 14 test5.cpp -o test5 E:\ MinGW \ lib \ libboost_random.a E:\ MinGW \ lib \ libboost_system.a工作,即产生一个列表每次运行不同的随机数。 – John