2016-02-29 130 views
-1

我需要一些隨機數進行模擬,並使用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目錄中可用。任何人都可以提出代碼或編譯有什麼問題嗎?

+0

boost :: random是一個編譯的boost庫,在你的命令行中你必須鏈接它來編譯這個程序,否則你會得到一個鏈接錯誤。 –

+0

好的,用g ++ -std = C++編譯test5.cpp 14 test5.cpp -o test5 E:\ MinGW \ lib \ libboost_random.a E:\ MinGW \ lib \ libboost_system.a工作,即產生一個列表每次運行不同的隨機數。 – John

回答

0

鏈接代碼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