制限されたセットのランダムな数値を返すクラスで、戻り値は重複しません.

5494 ワード

#include <vector>
using namespace std;

class RandomLimitNum
{
public:
RandomLimitNum(
int begin_num,int end_num);
bool GetCurrentRandomNum(int * result);
private:
vector
<int> m_vector;
};
#include "stdafx.h"
#include
"RandomLimitNum.h"

RandomLimitNum::RandomLimitNum(
int begin_num,int end_num)
{
for (int i = begin_num;i <= end_num; ++i)
{
m_vector.push_back(i);
}
}
bool RandomLimitNum::GetCurrentRandomNum(int * result)
{
size_t count
= m_vector.size();
if (count == 0)
{
return false;
}
else if (count == 1)
{
*result = m_vector[0];
m_vector.erase(m_vector.begin());
return true;
}
SYSTEMTIME st;
GetLocalTime(
&st);
srand(st.wSecond
*st.wMinute+st.wSecond);
int random = rand()%count;
*result = m_vector[random];
vector
<int>::iterator delete_it = m_vector.begin()+random;
m_vector.erase(delete_it);
return true;
}