如何在C 中每个应用程序一次播种MT19937并多次使用它

How to seed mt19937 once per app in C++ and use it multiple times?

本文关键字:MT19937 一次 应用程序      更新时间:2023-10-16

我可以在简单的应用中获得MT19937 RNG。现在,我试图将其播种一次,并在需要时多次使用它。这是我的代码。我遇到的错误是在GeneraterAndomNumber中 - " Gen:未宣布的标识符"。

main.cpp

#include <iostream>
#include "general.h"
int main() {
CallOncePerApp();
// Loop for output testing
// Ultimately, GenerateRandomNumber can be called from anywhere in any CPP file
for (int i=0;i<10;i++)  {
    int dwGen = GenerateRandomNumber(1, 1000);
    cout << dwGen; // print the raw output of the generator.
    cout << endl;
    }
}

General.h:

#include <random>
using namespace std;
extern random_device rd;
extern void CallOncePerApp();
extern mt19937 gen;
extern unsigned int GenerateRandomNumber(unsigned int dwMin, unsigned int dwMax);

General.cpp:

#include <random>
using namespace std;
random_device rd;
mt19937 gen;
void CallOncePerApp() 
{
    // Error C2064 term does not evaluate to a function taking 1 arguments
    gen(rd); // Perform the seed once per app
}
unsigned int GenerateRandomNumber(unsigned int dwMin, unsigned int dwMax) 
{
    uniform_int_distribution <int> dist(dwMin, dwMax); // distribute results between dwMin and dwMax inclusive.
    return dist(gen);
}

在这里,

mt19937 gen; // gen is an object of class mt19937! not a function
void CallOncePerApp() 
{
    // Error C2064 term does not evaluate to a function taking 1 arguments
    gen(rd); // **** therefore this line is wrong!
}

还需要在" eneral.cpp"文件中包含标头文件。