質問

I know that it is good practice to call srand() only once (otherwise, you might get similar sequences if called with the same seed). Now, I'm implementing a class that is going to be used in other codes (perhaps not mine), so I dont have access to main().

I'd like to know if there is any convention regarding the use of rand in classes ? Like some macro of function that test if srand has been called already (and if not, call it into the constructor or something). Or do I just trust the people who are going to use it to call srand() at the beginning of the main() ? Thank you,

EDIT @Malloc :

Thanks, so if I understand correctly, I'll have to use that type of initialization :

std::random_device r_device; 
std::default_random_engine r_engine (r_device());
std::uniform_real_distribution<double> uniform_noise (a,b); 

And then I can call the realisation with :

uniform_noise(r_engine);

And the seeding is not done with current time ? Therefore I can for example do the initialisation in the constructor and put the engine and the distribution as private members ?

役に立ちましたか?

解決

In modern C++, the use of rand() and srand() is not recommended.

You should use the C++11 <random> library instead.

Here you can get a good overview why <random> is better than rand().

Regarding your problem:

You can simply seed every random engine you want to use (e.g. std::default_radom_engine) with std::random_device whereever you want and should be save, or just use different engines (can be of the same type) in the different parts of your code and seed every one of them once.

他のヒント

This probably falls under the "document it" category. Clearly, calling srand() at some point in your library may prevent the other code from working as intended. So if your code is relying on srand having been called, then you need to explain in your documentation that you want the caller's code to call srand before using your functions.

As far as I know, there is no way to check if srand has indeed been called.

There may be other solutions, if you have restrictions on your environment. For example in glibc's rand and srand, you could use the rand_r which takes a pointer to a seed variable - so you can have your completely separate random number sequence, that is not dependent on outside "help".

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top