64,686
社区成员
发帖
与我相关
我的任务
分享
// Urand.h
#ifndef _URAND_H_
#define _URAND_H_
#include <bitset>
namespace zhcosin
{
template<std::size_t UpperBound>
class Urand
{
public:
Urand();
~Urand();
public:
std::size_t operator()();
private:
std::bitset<UpperBound> theBitSet;
};
} // namespace zhcosin
#endif //_URAND_H_
// Urand.cpp
#include "Urand.h"
#include <cstdlib>
#include <ctime>
namespace zhcosin
{
template<std::size_t UpperBound>
Urand<UpperBound>::Urand()
{
srand(time(0));
}
template<std::size_t UpperBound>
Urand<UpperBound>::~Urand()
{
}
template<std::size_t UpperBound>
std::size_t Urand<UpperBound>::operator ()()
{
if (theBitSet.count() == UpperBound)
theBitSet.reset();
std::size_t newVal;
while (theBitSet[newVal = rand() % UpperBound]);
theBitSet[newVal] = true;
return newVal;
}
} // namespace zhcosin
// main.cpp
#include <iostream>
#include "Urand.h"
int main(int argc, char *argv[])
{
zhcosin::Urand<10> a;
for (int i = 0; i < 10; i++)
{
std::cout << a() << ",";
}
std::cout << std::endl;
return 0;
}