Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use std::uniform_int_distribution<>::operator()

How to use operator()(Generator& g, const param_type& params); of std::uniform_int_distribution. This is my code

#include <iostream>
#include <random>

int get_random_int(const int lower_limit, const int upper_limit) {
   std::random_device rd{};
   std::mt19937 gen{rd()};

   static std::uniform_int_distribution<> dist;
   
   // use operator()(Generator& g, const param_type& params);
   return dist(gen, lower_limit, upper_limit);
}

int main() {
    std::cout << get_random_int(1, 1000000) << std::endl;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to create an object of type param_type.

    return dist(gen, std::uniform_int_distribution<>::param_type{lower_limit, upper_limit});

You can shorten the name to decltype(dist)::param_type, though the syntax isn’t much more readable in my opinion. Name alias would also make it shorter and cleaner.


Implicit construction with just {lower_limit, upper_limit} doesn’t work: https://godbolt.org/z/4cr3f758K, although I don’t see a requirement in cppreference that would mandate explicit constructor.


Also, note that the expensive part of the operation is setting up random number engine (here std::mt19937), not the distribution itself. It would be better (and easier) to make that static instead:

int get_random_int(const int lower_limit, const int upper_limit) {
    static std::random_device rd{};
    static std::mt19937 gen{rd()};
   
   return std::uniform_int_distribution{lower_limit, upper_limit}(gen);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading