does this look right
This compiles and still works fine on linux, can someone with windows tell me if I have it right for _WIN32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
/*
* rng.hpp
*
* Created on: Mar 25, 2013
* Author: michaela
*/
#ifndef RNG_HPP_
#define RNG_HPP_
#ifdef __linux__
#include <stdio.h>
class rng
{
FILE* rh;
public:
rng()
{
rh = fopen("/dev/urandom", "rb");
}
unsigned int next()
{
int ans;
fread(&ans, sizeof(int), 1, rh);
return ans;
}
};
#endif
#ifdef _WIN32
#include <time.h>
class rng
{
rng()
{
srand(time(NULL));
}
unsigned int next()
{
return rand();
}
};
#endif
#endif /* RNG_HPP_ */
|
specific parts of the code should be conditionally compiled rather the whole class. This is going to have lots of duplicate code.
I think I'd rather go with code that works on either. There's no reason for this to rely on O/S specific implementations.
Assuming your compiler supports C++11:
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <random>
class rng
{
public:
rng() : _engine(std::random_device()()) {}
unsigned next() { return _engine() ; }
private:
std::mt19937 _engine ;
};
|
If it doesn't you might consider using boost.
I'll take that as yes, but you recommend other ways.
I am using eclipse on ubuntu and so far cannot get c++11 to work
Ok, I got that working.
Thaks cire, seems to work pretty well :)
Topic archived. No new replies allowed.