C语言中提供了系统自带的随机函数srand(),但是这个函数真的很随机么,如果我们想让生成的随机数是我们给定的范围,应该如何做到呢,如果让一定范围内的数字都是以相同的概率出现又该如何实现呢,这些问题都是srand()所没有解决的, 下面的程序给出了某一范围内的相同概率出现的随机数生成器。 代码都已经调试过在VS2008上可以成功运行。这是无类型参数模板的经典应用。
#include "stdafx.h"
#include<iostream>
#include<bitset>
#include<cstddef>
#include<cstdlib>
#include<ctime>
using std::size_t;
using std::bitset;
time_t t;
template <size_t UpperBound> class Urand{
public:
Urand() { srand(clock());}
size_t operator () (); // function operator
private:
bitset<UpperBound> used;
};
template <size_t UpperBound> inline size_t Urand<UpperBound>::operator() ()
{
if(used.count() == UpperBound)
used.reset();
size_t newVal;
while(used[newVal = rand() % UpperBound])
;
used[newVal] = true;
return newVal;
}
int _tmain(int argc, _TCHAR* argv[])
{
Urand<100> myRand;
for(int i=0; i< 100; i++)
std::cout<<myRand()<<" "<<std::endl;
return 0;
}
对于某一范围的随机数只需要将上面的模板参数增加一个LowerBound即可。
例如: template <size_t LowerBound=10, size_t UpperBound=20> class Urand
转载于:https://blog.51cto.com/zyh2000/372427