用C ++队列写一个医院挂号系统并给出解释
时间: 2023-12-29 12:05:05 浏览: 25
以下是使用C++队列实现的医院挂号系统的代码:
```
#include <iostream>
#include <string>
#include <queue>
using namespace std;
class Patient {
private:
string name;
int age;
string gender;
string disease;
public:
Patient(string n, int a, string g, string d) {
name = n;
age = a;
gender = g;
disease = d;
}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
cout << "Disease: " << disease << endl;
}
};
class Hospital {
private:
queue<Patient> patients;
public:
void addPatient(Patient p) {
patients.push(p);
cout << "Patient added successfully!" << endl;
}
void displayPatients() {
if (patients.empty()) {
cout << "No patients in queue." << endl;
return;
}
queue<Patient> temp(patients);
while (!temp.empty()) {
temp.front().display();
cout << endl;
temp.pop();
}
}
void servePatient() {
if (patients.empty()) {
cout << "No patients in queue." << endl;
return;
}
patients.front().display();
cout << " has been served." << endl;
patients.pop();
}
};
int main() {
Hospital hospital;
string name, gender, disease;
int age;
int choice;
do {
cout << "1. Add Patient" << endl;
cout << "2. Display Patients" << endl;
cout << "3. Serve Patient" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter patient name: ";
cin >> name;
cout << "Enter patient age: ";
cin >> age;
cout << "Enter patient gender: ";
cin >> gender;
cout << "Enter patient disease: ";
cin >> disease;
Patient p(name, age, gender, disease);
hospital.addPatient(p);
break;
case 2:
hospital.displayPatients();
break;
case 3:
hospital.servePatient();
break;
case 4:
cout << "Exiting program..." << endl;
break;
default:
cout << "Invalid choice! Try again." << endl;
break;
}
} while (choice != 4);
return 0;
}
```
这个程序使用了STL库中的queue来实现医院挂号系统。Patient类表示患者,包含姓名、年龄、性别和疾病等信息,并有一个display方法用于显示患者信息。Hospital类表示医院,包含一个患者队列,有三个方法:addPatient用于添加患者到队列中,displayPatients用于显示所有患者的信息,servePatient用于表示医院已经为队列中的第一个患者提供了服务。
在主函数中,我们首先创建了一个Hospital对象,并通过一个do-while循环来提供用户菜单选择。用户可以选择添加患者、显示所有患者信息、为队列中的第一个患者提供服务或退出程序。当用户选择添加患者时,程序会提示用户输入患者姓名、年龄、性别和疾病等信息,并创建一个Patient对象,然后将该对象添加到Hospital对象的患者队列中。当用户选择显示所有患者信息时,程序会遍历Hospital对象的患者队列,并调用每个患者对象的display方法来显示其信息。当用户选择为队列中的第一个患者提供服务时,程序会显示第一个患者的信息,并将其从患者队列中移除。
这个程序可以作为医院挂号系统的一个简单实现,使用队列来存储患者信息,保证了按照先来后到的顺序进行服务。同时,队列的FIFO(先进先出)特性也符合了医院挂号系统的实际需求。