## 如何在编译时生成C++中的随机数？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (42)

```using namespace std;
#include <iostream>
#include <vector>
#include <random>

vector<double> rands;
typedef std::mt19937_64 RNG;
uint64_t seed_val;
RNG rng;

void initialize() {
rng.seed(seed_val);
}

constexpr vector<double> generate_random( )                 //size_t numbers)
{
int numbers = 1000;
std::uniform_real_distribution<double> zero_one(0.0, 1.0);
for (unsigned int i = 0; i < numbers; i++) {
double rand_num = zero_one(rng);
rands.push_back( rand_num );
}
return rands;
}

int main()
{
cout << "TMP rands";
for_each( rands.begin(), rands.end(), [] (double value)
{
cout<<value<<endl;
});
}```

```template<u32 S, u32 A = 16807UL, u32 C = 0UL, u32 M = (1UL<<31)-1>
struct LinearGenerator {
static const u32 state = ((u64)S * A + C) % M;
static const u32 value = state;
typedef LinearGenerator<state> next;
struct Split { // Leapfrog
typedef LinearGenerator< state, A*A, 0, M> Gen1;
typedef LinearGenerator<next::state, A*A, 0, M> Gen2;
};
};```

### 2 个回答

```g++ -D__RANDOM__=\$RANDOM yourprog.cpp -o yourprog

//yourprog.cpp
#include <iostream>
int main() {
std::cout << "Random variable " << __RANDOM__ << std::endl;
return 0;
}```

```//DevRandomGenerator.cpp
#include <iostream>
#include <fstream>

class DevRandom {
private:
std::ifstream stream;
public:

DevRandom() {
stream.open("/dev/urandom",std::ios::in|std::ios::binary);
}

unsigned int unsignedInt() {
unsigned int u = 0;
return u;
}
};

int main() {
DevRandom rand;
std::cout << rand.unsignedInt() << std::endl;
return 0;
}```

```g++ DevRandomGenerator.cpp -o DevRandomGenerator
g++ -D__RANDOM__="\$(./DevRandomGenerator)" yourprog.cpp -o yourprog```