项目描述说明
1.目的: 获取进出电梯人数及姓名,并打印出来
2.思路:
1.抽象人员
2.抽象电梯(list)
3.进电梯的人(queue)
4.把进电梯和出电梯的人拷贝一份放入vector中,待打印
3.流程:
1.电梯上升
2.创建人员
3.判断进电梯条件,然后进电梯
4.判断出电梯条件,然后出电梯
5.打印出电梯和进电梯人员的人数和姓名
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include <string>
#include <ctime>
#include <vector>
#include <list>
#include <queue>
const int MaxFloor = 28;
const int MaxCarCapacity = 25;
class Person
{
public:
string name;
};
//创建电梯门口等待人类队列
void CreateWaitingPeople(queue<Person>&waiting_people,int floor)
{
//门口至少1人入队,至多10人入队
int wait_num = rand() % 10 + 1;
string SetName = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < wait_num; i++)
{
Person p;
char buf[64] = { 0 };
sprintf(buf, "%d", floor);
p.name = buf;
p.name += "楼";
p.name += SetName[i];
waiting_people.push(p);
}
}
//进入电梯
void PushPerson(list<Person>&lift_car, queue<Person>&waiting_people, vector<Person>&push_person, int&push_num)
{
while (!waiting_people.empty())
{
//电梯满员时,跳出循环,无法再进入乘客
if (lift_car.size()==MaxCarCapacity)
{
break;
}
lift_car.push_back(waiting_people.front());
push_person.push_back(waiting_people.front());
waiting_people.pop();
push_num++;
}
}
//出去电梯
void PopPerson(list<Person>&lift_car, vector<Person>&pop_person, int &pop_num)
{
int out_num = rand() % 10;
for (int i = 0; i < out_num;i++)
{
//电梯清空时,直接跳过出电梯
if (lift_car.empty())
{
break;
}
pop_person.push_back(lift_car.front());
lift_car.pop_front();
pop_num++;
}
}
//打印进入人员名单
void PrnPushPerson(vector<Person>&push_person)
{
for (vector<Person>::iterator it = push_person.begin();it!=push_person.end();it++)
{
cout << it->name << endl;
}
}
//打印出去人员名单
void PrnPopPerson(vector<Person>&pop_person)
{
for (vector<Person>::iterator it = pop_person.begin(); it != pop_person.end(); it++)
{
cout << it->name << endl;
}
}
//业务流程:
//电梯链表(电梯轿厢),每层电梯人员队列,vector容器记录所有出入电梯人员
//抽象思路:通过一个电梯循环系统,每到达一层,电梯链表(电梯轿厢)中会有人出入,进入的人员由每层人员队列决定(随机),出电梯人员随机
void test()
{
//设置随机数种子
srand((unsigned int)time(NULL));
list<Person> lift_car;
vector<Person> push_person;
vector<Person> pop_person;
int pop_num = 0, push_num = 0;
//电梯动力系统
for (int i = 1; i <= MaxFloor;i++)
{
queue<Person> waiting_people;
//创建电梯口随机等待人员队列
CreateWaitingPeople(waiting_people,i);
//开始出电梯
if (i!=1)
{
if(lift_car.size()>0)
{
if(i==MaxFloor)
{
cout << "清空电梯" << endl;
while(!lift_car.empty())
{
pop_person.push_back(lift_car.back());
pop_num++;
lift_car.pop_back();
}
}
else
{
PopPerson(lift_car, pop_person, pop_num);
}
}
}
//开始进电梯
if (i<MaxFloor && lift_car.size()<MaxCarCapacity)
{
PushPerson(lift_car, waiting_people, push_person, push_num);
}
}
//打印进入人员名单
PrnPushPerson(push_person);
//打印进入人员人数
cout << "共进入" << push_num << "人." << endl;
//打印出去人员名单
PrnPopPerson(pop_person);
//打印出去人员人数
cout << "共出去" << pop_num << "人." << endl;
}
int main()
{
test();
system("pause");
return 0;
}