dimanche 5 juin 2016

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

I have a typedef for some arbitrary integer type, e.g.

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.




Aucun commentaire:

Enregistrer un commentaire