public
Created

Show usage of C++ random (tr1 or C++11)

  • Download Gist
random_example1.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.