我的想法是先创建一个Person类包含自身序号和数字,在借助vector容器从而实现,人数和出局数字都经过宏定义来实现,便于代码后续维护和修改
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#define Num_person 10
#define Num_out 3
using namespace std;
class Person
{
public:
Person(int h, int n)
{
this->m_hao = h;
this->m_num = n;
}
int m_hao;
int m_num;
};
class Myprint
{
public:
void operator()(Person& p)
{
cout << "编号为" << p.m_hao << "数字为" << p.m_num << endl;
}
};
vector<Person> init_vector()
{
vector<Person> v;
for (int i = 1; i < Num_person; i++)
{
Person p(i, 0);
v.push_back(p);
}
return v;
}
void printPerson(vector<Person>& v)
{
for_each(v.begin(), v.end(), Myprint());
}
void Random(vector<Person>& v)
{
random_shuffle(v.begin(), v.end());
cout << "随机后的排序为:" << endl;
//printPerson(v);
}
void kick_person(vector<Person>& v) //出局函数
{
for (vector<Person>::iterator it = v.begin(); it != v.end(); )
{
if (it->m_num == Num_out)
{
it = v.erase(it); //erase的返回值为下一个元素的地址
}
else
it++;
}
}
void Num_Assgin(vector<Person>& v) //给人排号
{
static int j = 1;
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) //分配数字
{
it->m_num = j++;
if (j == Num_out + 1)
j = 1;
}
}
void Joseph(vector<Person>& v)
{
Num_Assgin(v);
printPerson(v);
cout << endl;
while (v.size() != 1)
{
kick_person(v);
printPerson(v);
cout << endl;
Num_Assgin(v);
}
cout << endl;
printPerson(v);
}
int main()
{
srand((unsigned int)time(NULL));
vector<Person> v = init_vector();
Random(v);
Joseph(v);
/*kick_person(v);
cout << endl;
printPerson(v);*/
return 0;
}