随机数引擎和分布
17.28 编写函数,每次调用生成并返回一个均匀分布的随机unsigned int。
#include<iostream> #include<vector> #include<random> #include<ctime> using namespace std; int main() { uniform_int_distribution<unsigned> u; default_random_engine e(); for(size_t i=0;i<10;++i) cout<<u(e)<<" "; cout<<endl; for(size_t i=0;i<10;++i) cout<<u(e)<<" "; cout<<endl; }
17.29 允许用户提供一个种子作为可选参数。
17_29.cpp #include<iostream> #include<vector> #include<random> #include<ctime> using namespace std; int main() { uniform_int_distribution<unsigned> u; default_random_engine e(time(0)); for(size_t i=0;i<10;++i) cout<<u(e)<<" "; cout<<endl; for(size_t i=0;i<10;++i) cout<<u(e)<<" "; cout<<endl; }
17.30 此次增加两个参数,表示函数允许返回的最小值和最大值
#include<iostream> #include<vector> #include<random> #include<ctime> using namespace std; int main() { uniform_int_distribution<unsigned> u(0,9); default_random_engine e(time(0)); for(size_t i=0;i<10;++i) cout<<u(e)<<" "; cout<<endl; for(size_t i=0;i<10;++i) cout<<u(e)<<" "; cout<<endl; }