(例子)无重复随机数生成器

来源:互联网 发布:cdx什么意思网络用语 编辑:程序博客网 时间:2024/06/05 03:03
#ifndef URAND_H
#define URAND_H
#include<bitset>
#include<cstddef>
#include<cstdlib>
#include<ctime>
#include<iostream>
using std::size_t;
using std::bitset;
using namespace std;
template<size_t UpperBound>class Urand
{
bitset<UpperBound> used;
                                                               //..bitset<n> b;
                                                                       //..b有n位,每位都为0.参数n可以为一个表达式.
                                                                       //..如bitset<5> b0;则"b0"为"00000"
public:
Urand(){srand(time(0));}
size_t operator()();
};
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;
}
#endif
int main()
{
Urand<10>u;
for(int i=0;i<10;i++)//产生10以内的无重复数据
cout<<u()<<",";
cout<<"\n10个以内无重复..."<<endl;
for(int i=0;i<20;i++)
cout<<u()<<",";
return 0;
}
0 0
原创粉丝点击