【问题标题】:MinGW boost random_device compile errorMinGW boost random_device 编译错误
【发布时间】: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


【解决方案1】:

将代码链接到 boost 库 libboost_random.alibboost_system.a 似乎可以解决问题,可执行文件会为每次运行生成不同随机数的列表。

// test5.cpp
// MinGW Distro - nuwen.net
// g++ -std=c++14 test5.cpp -o test5 E:\MinGW\lib\libboost_random.a E:\MinGW\lib\libboost_system.a

#include <boost/random.hpp>
#include <boost/random/random_device.hpp>
#include <iostream>
#include <random>

using namespace std;
int main(){
    boost::random_device rd;
    boost::mt19937 mt(rd());
    uniform_int_distribution<int> dist(0,99);
    for (int i = 0; i< 16; ++i){
        cout<<dist(mt)<<" ";
        }
        cout <<endl;
}

运行 1:20 89 31 30 74 3 93 43 68 4 64 38 74 37 4 69

运行 2:40 85 99 72 99 29 95 32 98 73 95 88 37 59 79 66

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2014-02-26
    相关资源
    最近更新 更多