#include <iostream>
#include <random>
int gen_ran(void)
{
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<int> dist(0, 9);
return dist(gen);
}
int main()
{
for (int i = 0; i < 50; i++)
{
std::cout << gen_ran() << " ";
if ((i + 1) % 10 == 0)
std::cout << std::endl;
}
}
I don't quite understand why we may put a static in each one of the three lines in the gen_ran() function. I googled a lot but it seems there are no clear answers.
My understanding is by using a static, we only initialize the objects once but the algrithms within each class (random_device, mt19937, uniform_int_distribution) can still generate random numbers. So static can save some computer resources when the function is called many times?
How about if I don't use any static or use one or two in the code. Does it make any difference if I don't in each case? Thanks very much.
Aucun commentaire:
Enregistrer un commentaire