/**
* 作者: cwl
* 描述: c++ 随机数引擎生成随机数
* */
#include <bits/stdc++.h>
using namespace std;
template <typename T>
void printVector(std::vector<T> &vec, int index = 0) {
cout << "[" << index << "] ";
for(auto &iter: vec) {
cout << "" << iter << " ";
}
cout << endl;
}
int main()
{
//随机数普遍是通过线性同余运算产生的为伪随机,之前我们用rand() % mod
//这里我们尝试随机数引擎
auto randomVectorUnsigned = [](int count) -> vector<unsigned int> {
int random_seed = time(0);
//可以用下面两种方式设置seed
default_random_engine e(random_seed);
e.seed(random_seed);
//随机数
uniform_int_distribution<unsigned int>u(0, 100);
vector<unsigned int>vec;
for(auto i = 1; i <= count; ++i) {
vec.push_back(u(e));
}
return vec;
};
vector<unsigned int> test_int = randomVectorUnsigned(10);
printVector(test_int, 1);
auto randomVectorDouble = [](int count) -> vector<double> {
int random_seed = time(0);
//可以用下面两种方式设置seed
default_random_engine e(random_seed);
e.seed(random_seed);
//随机数
uniform_real_distribution<double>u(0, 10);
vector<double>vec;
for(auto i = 1; i <= count; ++i) {
vec.push_back(u(e));
}
return vec;
};
vector<double> test_double = randomVectorDouble(10);
printVector(test_double, 2);
//生成非均匀的随机数
auto randomVector = [](int count) -> vector<double> {
int random_seed = time(0);
//可以用下面两种方式设置seed
default_random_engine e(random_seed);
e.seed(random_seed);
//随机数
normal_distribution<> n(4, 1.5); //均值4,标准差1.5;
vector<double>vec;
for(auto i = 1; i <= count; ++i) {
vec.push_back(n(e));
}
return vec;
};
vector<double> test = randomVector(10);
printVector(test);
return 0;
}