jeudi 3 décembre 2015

Why mt19937 m(random_device()()) cannot compile?

I want to create a function which returns the index of vector randomly according to the value of element as probability:

float getRandomIndex(const vector<float>& v){
    random_device r;
    mt19937 m(r());
    return discrete_distribution<>(v.begin(),v.end())(m);
}

int main(){
    for(int i=0;i<10;i++){
        vector<float> a{0.9,0.1};
        cout << getRandomIndex(a) << endl;
    }
    return 0;
}

now I want to reduce line numbers, so try to rewrite the function as:

float getRandomIndex(const vector<float>& v){
    mt19937 m(random_device()());
    return discrete_distribution<>(v.begin(),v.end())(m);
}

but failed to compile:

error: function cannot return function type 'std::__1::random_device ()'
mt19937 m(random_device()());
                       ^
warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
mt19937 m(random_device()());
         ^~~~~~~~~~~~~~~~~~~
note: add a pair of parentheses to declare a variable
mt19937 m(random_device()());
          ^
          (

1 warning and 1 error generated.

but I try

random_device r;
cout << r() << endl;

and

cout << random_device()() << endl;

they seems have the same function, why I cannot replace the variable r to a immediately created random_device in mt19937?




Aucun commentaire:

Enregistrer un commentaire