- 前言
- 一、随机数生成封装
- 二、使用示例
前言
最近有随机数使用需求,但是rand()是伪随机数,不符合使用条件,因此基于C++11最新标准,实现符合自己需求的随机数类。
一、随机数生成封装
#include二、使用示例#include class CIntRand { public: CIntRand(int begin = 0, int end = std::numeric_limits ::max()) : m_dis(begin, end), m_engine(std::random_device{}()) { // std::random_device 均匀分布整数随机数生成器 } ~CIntRand() {} int operator()() { return m_dis(m_engine); } ///< 不允许拷贝、赋值 CIntRand(const CPscIntRand&) = delete; void operator=(const CPscIntRand&) = delete; private: std::uniform_int_distribution m_dis; //均匀分布类模板,限定生成的随机数的范围 std::mt19937 m_engine; //梅森旋转算法伪随机数引擎 };
int main()
{
//生成 10 个位于 0 - 100 的随机数
CIntRand test(0, 100);
for(int i=0; i<10; i++)
{
std::cout << test() << "n";
}
return 0;
}



