how would i generate a seed or hash that would make rand actually random? I need it to change every time it picks a number. New to c++ so i'm not exactly sure how to do this. Thanks! :D
Asked
Active
Viewed 924 times
6
-
@DevanshMohanKaushik -- The referenced question/answers in your suggested duplicate is a bad suggestion, as they advocate use of time as a seed -- which is bad practice and can lead to duplicate random numbers between processes that seed at the same time (think web servers) – Soren Mar 29 '16 at 05:40
-
@soren it also contains the links to the other useful answers including the one you mentioned in the coment section. – Hummingbird Mar 29 '16 at 05:57
-
This question is for C++ while the duplicate marked is asking for C. – Utkarsh Bhardwaj Mar 29 '16 at 16:58
2 Answers
5
With C++11 you can use std::random_device
. I would suggest you to watch link for a comprehensive guide.
Extracting the essential message from the video link : You should never use srand
& rand
, but instead use std::random_device
and std::mt19937
-- for most cases, the following would be what you want:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(0,99);
for (int i = 0; i < 16; i++) {
std::cout << dist(mt) << " ";
}
std::cout << std::endl;
}

Utkarsh Bhardwaj
- 650
- 6
- 7
1
There is no such thing as an "actually random" random number generator without sampling environmental data or accessing a quantum random number source. Consider accessing the ANU random number source if you require truly random numbers (http://qrng.anu.edu.au/FAQ.php#api).
Otherwise, Boost provides a more robust pseudo-RNG, which should suffice for most purposes: http://www.boost.org/doc/libs/1_58_0/doc/html/boost_random.html

manglano
- 844
- 1
- 7
- 21
-
3Note that much of boost random was standardized with c++11, and can be accessed through `
`. – Yuushi Mar 29 '16 at 05:30