问题描述:男士和女士排成一排进入舞厅,按序分成男队和女队,依次从男队头和女队头各出一人结成舞伴,未配对的等待下轮配对。
#include <queue>
class dancer {
public:
char name;
char sex;
};
int main()
{
srand((unsigned int)time(0) + rand());
string nameSeed = "ABCDEFGHIJKLMNOPQ";//姓名种子
string sexSeed = "FM";//F表示女士,M表示男士
vector<dancer> v;//表示排成一列的男士和女士
for (int i = 0; i < 10; i++) {//随机创建10名舞者
dancer d;
int sex = rand() % 2;
d.name = nameSeed[i];
d.sex = sexSeed[sex];
v.push_back(d);
}
random_shuffle(v.begin(), v.end());
cout << "舞者如下:" << endl;
for (vector<dancer>::iterator it = v.begin(); it != v.end(); it++)//打印这10位舞者
cout <<"姓名:" << it->name <<" "<<"性别:" << it->sex << endl;
queue<dancer> Mdancer, Fdancer;//Mdancer用于存放男士,Fdancer用于存放女士
for (int i = 0; i < v.size(); i++) {
if (v[i].sex == 'F')//如果是男士则放入男队中
Fdancer.push(v[i]);
else//女士放入女队中
Mdancer.push(v[i]);
}
cout << endl;
while (!Mdancer.empty() && !Fdancer.empty()) {//舞者配对
cout << "舞伴:" << Mdancer.front().name << "和" << Fdancer.front().name << endl;
Mdancer.pop();//配对成功出队
Fdancer.pop();
}
cout << endl << "未配对的舞者有:";
while (!Mdancer.empty()) {
cout << Mdancer.front().name << ' ';
Mdancer.pop();
}
while(!Fdancer.empty()){
cout << Fdancer.front().name << ' ';
Fdancer.pop();
}
}