编写一个程序,定义结构teacher,包括姓名,年龄,工号,电话,住址等信息。用动态分配new开辟包含5个teacher的数组,然后实现输入,按年龄排序,按姓名查找,输出等功能。用函数的形式实现这些功能。
时间: 2023-06-14 13:03:54 浏览: 155
TeachMgrv1.0.rar_teacher appraisal_tflathintunit_人口信息管理_测评系统程序_项
以下是用C++实现的程序:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct teacher {
string name;
int age;
string id;
string phone;
string address;
};
bool cmp_teacher_age(const teacher &a, const teacher &b) {
return a.age < b.age;
}
void input_teachers(teacher *t, int n) {
for (int i = 0; i < n; i++) {
cout << "输入第" << i+1 << "个教师信息:" << endl;
cout << "姓名:";
cin >> t[i].name;
cout << "年龄:";
cin >> t[i].age;
cout << "工号:";
cin >> t[i].id;
cout << "电话:";
cin >> t[i].phone;
cout << "住址:";
cin >> t[i].address;
}
}
void sort_teachers_by_age(teacher *t, int n) {
sort(t, t+n, cmp_teacher_age);
}
void print_teachers(teacher *t, int n) {
for (int i = 0; i < n; i++) {
cout << "姓名:" << t[i].name << endl;
cout << "年龄:" << t[i].age << endl;
cout << "工号:" << t[i].id << endl;
cout << "电话:" << t[i].phone << endl;
cout << "住址:" << t[i].address << endl;
}
}
void find_teacher_by_name(teacher *t, int n, const string &name) {
bool found = false;
for (int i = 0; i < n; i++) {
if (t[i].name == name) {
cout << "姓名:" << t[i].name << endl;
cout << "年龄:" << t[i].age << endl;
cout << "工号:" << t[i].id << endl;
cout << "电话:" << t[i].phone << endl;
cout << "住址:" << t[i].address << endl;
found = true;
break;
}
}
if (!found) {
cout << "没有找到姓名为" << name << "的教师!" << endl;
}
}
int main() {
int n = 5;
teacher *t = new teacher[n];
input_teachers(t, n);
cout << endl;
cout << "按年龄排序后:" << endl;
sort_teachers_by_age(t, n);
print_teachers(t, n);
cout << endl;
cout << "请输入要查找的教师姓名:";
string name;
cin >> name;
cout << "查找结果:" << endl;
find_teacher_by_name(t, n, name);
cout << endl;
delete[] t;
return 0;
}
```
程序中定义了一个teacher结构体,包括姓名、年龄、工号、电话、住址等信息。程序中通过动态分配new开辟了一个包含5个teacher的数组。然后定义了几个函数,分别实现了输入、按年龄排序、按姓名查找、输出等功能。
程序的执行流程是:
1. 调用input_teachers函数输入5个教师的信息;
2. 调用sort_teachers_by_age函数按年龄排序;
3. 调用print_teachers函数输出排序后的结果;
4. 调用find_teacher_by_name函数按姓名查找教师信息;
5. 释放动态分配的内存。
以上程序可以满足题目的要求。
阅读全文