lundi 25 février 2019

C++

beginner at C++ here.

I have been generating random numbers in C++ using the following function:

double randDouble() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(1.0, 10.0);
    return dist(mt);
}

I was wondering why I am unable to do this in say a single line, (using temporary objects) like so:

double randDouble2() {
    return std::uniform_real_distribution<double>{1.0, 10.0}(std::default_random_engine(std::random_device{}()));
}

I think I read somewhere it is something to do with the default constructor not being explicit for these classes, but I'm not really sure what to search to find out whether I am correct?

I have also read that this would be bad practice since creating a new random_device for every call would be quite expensive, however, I am interested in why the one-liner is not possible rather than not practical - that is to say I am interested in the general case for creating anonymous objects (unsure whether this is the right term).




Aucun commentaire:

Enregistrer un commentaire