My end goal is to have a function to generate max-range/min-range random numbers for each type in cstdint. These functions are for a header file that I will be using long term.
My first instinct was to do rand() way. However, this is 'outdated' for long-term use. See here.
The best way I found in many YouTube tutorials / websites is using the library, more specifically, forming a distribution and choose a spot in the distribution from the mt19937_64
generator.
To save some calculations/processing, I decided to create this function that will be used in all the random_int functions (instead of creating a gen every time I get a random number).
// only creates a gen once and returns the same gen
extern std::mt19937_64 random_generator(){
static std::mt19937_64 gen(std::random_device{}());
return gen;
}
I want to avoid the use of a global variable. This function works as intended as far as I have tested it.
TL,DR : This is the main issue I am having.
Generating a random number generators random things like {2,^,F,$,...etc}
This is the function. Just note, there are a few typedefs that should be self-explanatory. i.e. int8 = int8_t
extern inline int8 random_int8(){
std::mt19937_64 gen = random_generator();
// since I will be using this for int64_t, not sure what to put in the <>, this problem still exist with int though.
std::uniform_int_distribution<> distrib{
// min and max returns correct values (tested), static cast is needed
static_cast<int8>( std::numeric_limits<int8>::min() ),
static_cast<int8>( std::numeric_limits<int8>::max() )
};
return static_cast<int8>( distrib(gen) );
}
If I do std::cout << distrib(gen) << std::endl
before the function ends, it correctly displays the number. However, if you type_cast, it messes up even though its in range. Why?
Aucun commentaire:
Enregistrer un commentaire