如何在C ++中为每个应用程序播种一次mt19937并多次使用它?

问题描述 投票:0回答:1

我可以在一个简单的应用程序中获得mt19937 rng种子。现在我试图让每个应用程序播种一次,并在需要时多次使用它。这是我的代码。我得到的错误是GenerateRandomNumber - “gen:undeclared identifier”。

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);
}
c++ windows random random-seed mt19937
1个回答
0
投票

这里,

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!
}

您还需要在“general.cpp”文件中包含头文件。

© www.soinside.com 2019 - 2024. All rights reserved.