mardi 31 juillet 2018

Function using older class declaration before ctor

I've written the following to generate random numbers biased around a mean:

#include <random>
#include <iostream>

using namespace std;

random_device rd;
mt19937_65 eng(rd());
piecewise_linear_distribution<double> burst_distr;

void foo()
{
    double x = burst_distr(eng);
    cout << "Foo Burst: " << x << endl;
}

int main()
{
   double min, max, avg;
   cout << "MINIMUM NUMBER OF PROCESS BURST UNITS:" << endl;
   cin >> min;
   cout << "MAXIMUM NUMBER OF PROCESS BURST UNITS:" << endl;
   cin >> max;
   cout << "AVAGAGE NUMBER OF PROCESS BURST UNITS:" << endl;
   cin >> avg;
   double mean = (3 * avg) - max - min;
   piecewise_linear_distribution<double> burst_distr({ min, mean, max }
                                                     [mean_bound](double x) 
                                                     {
                                                         return x == mean_bound ? 1.0 : 0.0; 
                                                     }
                                                    );

    for (int i = 0; i < 100; ++i)
    {
        foo();
        cout << "Local Burst: " << burst_distr(eng) << endl; 
    }
    return 0;
};

When I run this however, foo() generates random numbers between 0 and 1 while the local call to burst_distr generates numbers within the range supplied.

It appears that declaring burst_distr before foo() has foo() point back to that uninitialized object but then initializing again with the same name later in main() does not update or overwrite the object in the namespace.

I've not encountered this behavior before, but how can I declare a class prior to a function definition and then call its ctor later?

Aucun commentaire:

Enregistrer un commentaire