Skip to content

Instantly share code, notes, and snippets.

@DarrenCook
Created March 1, 2012 00:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarrenCook/1946214 to your computer and use it in GitHub Desktop.
Save DarrenCook/1946214 to your computer and use it in GitHub Desktop.
Show usage of C++ random (tr1 or C++11)
#include <iostream>
#include <boost/tr1/random.hpp>
//#include <tr1/random.hpp> //If your compiler supports it
//#include <random> //If using c++11; then the "tr1::" prefixes can be removed.
using namespace std;
//Random number generator can be global. Use a mutex if program is multi-threaded.
tr1::mt19937 random_generator;
int main(int,char**){
//Set the random seed for the random number generator
// (the default would be the same numbers every time)
random_generator.seed(time(NULL));
//Create an object that will generate numbers from 1 to 10 inclusive
tr1::uniform_int<int> dice10(1,10);
//A loop to generate 20 numbers. Notice how we pass a random number
// generator to a number distribution object.
for(int index=0; index<20; index++)
cout << dice10(random_generator) << endl;
}
@DarrenCook
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment