I want to generate unique random number sequence in QT, Using QDateTime::currentDateTime().toTime_t() as seed value, will qrand() generate unique random numbers?
问题:
回答1:
No. qrand
can only generate as many unique numbers as fit into an integer, so -- whatever the implementation -- you cannot count on uniqueness.
Also, knowing that a different seed creates a different random integer would yield a level of predictability that effectively makes qrand
not random anymore.
Edit: I swear I'm not trying to make fun of you by posting a cartoon; I think this is a quite good explanation of the problem:
(source: dilbert.com)
回答2:
Depending on how you store your session ids, you can generated a (mostly) guaranteed unique identifier by using a UUID. See the documentation for QUuid
. Also be aware of this (bold added):
You can also use
createUuid()
. UUIDs generated bycreateUuid()
are of the random type. TheirQUuid::Version
bits are set toQUuid::Random
, and theirQUuid::Variant
bits are set toQUuid::DCE
. The rest of the UUID is composed of random numbers. Theoretically, this means there is a small chance that a UUID generated bycreateUuid()
will not be unique. But it is a very small chance.
I can vouch for the fact that those generated UUIDs won't necessarily be unique, so if you do need them to be unique, look into libuuid
or something similar.
回答3:
According to the Qt Documentation, QRand is just a thread-safe version of the standard rand(), I wouldn't assume the method used is any more secure/superior to that of rand() based on that description.
I think you need to use different terminology than 'unique' random numbers (no Psuedo-Random Number Generator will produce a unique stream, as input X will always produce output Y). What's the actual situation?