Note that there are some explanatory texts on larger screens.

plurals
  1. POHow often should I reseed in C++?
    text
    copied!<p>I just wonder if it is enough to seed the random number generator only once at the beginning of a program. I write functions which uses random numbers. I never seed the rand() generator within the function, but rather leave calling srand() on main entry. E.g. my program may look like:</p> <pre><code>void func1() { std::cout &lt;&lt; "This is func1 " &lt;&lt; std::rand() &lt;&lt; std::endl; } void func2() { std::cout &lt;&lt; "This is func2 " &lt;&lt; std::rand() &lt;&lt; std::endl; } int main() { std::srand(std::time(NULL)); func1(); func2(); return 0; } </code></pre> <p>By doing so, I can easily switch off seeding from the main entry. It comes useful when debugging a program - the results are kept the same every time I run the program without seeding. Sometimes, if a problem occurs due to some random number, it may just disappear if a different set of random numbers is to be generated, so I'd prefer such a simple mechanism to switch off seeding.</p> <p>However, I noticed in C++11's new random utility set, the random number generator has to be instantiated before using. (e.g. default_random_engine). And every time a generator has to be seeded separately. I wonder if it is actually encouraged to reseed the generator whenever a new generator is needed. I know I could create a global random generator and seed it only once as before, but I don't really like the idea of using global variables at all. Otherwise, if I create a local random number generator, I sort of lose the ability to globally switch off seeding for debugging or whatever purpose.</p> <p>I'm excited to learn the new features in C++11, but sometimes it's just very confusing. Can anyone let me know if I got anything wrong with the new random generators? Or what might be the best practice in C++11?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload