简体   繁体   中英

C++ random number for arbitrary integer (of fundamental type)

I have a typedef for some arbitrary integer type, eg

typedef unsigned long long myint;

in other words, I don't know how it's actually defined, but I can guarantee that it's a fundamental type .

I also have a variable instance of this type

myint n;

How do I assign n a random value that could be any value supported by myint ?


Simply scaling the result of rand() to cover the range of myint would not be suitable since myint will likely be larger than the int type and therefore there will be inaccessible numbers.

Something like the following would work but seems rather inelegant and inefficient: Find the number of bits in myint and in int , and then concatenate a bunch of rand() numbers until myint is filled.

With the C++11 <random> library, uniform_int_distribution can give you any integer type:

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<myint> dis(
    std::numeric_limits<myint>::min(), 
    std::numeric_limits<myint>::max());

myint num = dis(gen);

With unsigned types you can use the default constructor for uniform_int_distribution , which gives the range 0 to numeric_limits<T>::max() .

Use the #include <random> library functions!


As a bonus, those functions guarantee that the integers will be uniformly distributed across the given range.

//Initialize random engine
std::random_device rd;
std::mt19937 mt{ rd() };
std::uniform_int_distribution<myint> uid; //Default constructor - Range is 0 to myint-max

//'num' is random!
myint num = uid(mt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM