优化修改代码,分别按照“系”进行学历统计,分别计算每个系中各学历的人数:void countEducation() { Node* p = head->next; int bachelorCount = 0, masterCount = 0, doctoralCount = 0; while (p != nullptr) { if (p->data.getEducation() == "本科") { bachelorCount++; } else if (p->data.getEducation() == "硕士") { masterCount++; } else if (p->data.getEducation() == "博士") { doctoralCount++; } p = p->next; } cout << "本科:" << bachelorCount << endl; cout << "硕士:" << masterCount << endl; cout << "博士:" << doctoralCount << endl; }
时间: 2024-02-02 09:04:57 浏览: 64
可以使用一个嵌套的 map 来记录各系对应的各个学历的人数,然后遍历链表统计即可,代码如下:
```c++
void countEducation() {
Node* p = head->next;
map<string, map<string, int>> educationCount; // 用 map 记录各个系对应的各个学历的人数
while (p != nullptr) {
educationCount[p->data.getDepartment()][p->data.getEducation()]++;
p = p->next;
}
for (const auto& [department, educationMap] : educationCount) {
cout << department << "系:" << endl;
for (const auto& [education, count] : educationMap) {
cout << education << ":" << count << endl;
}
cout << endl;
}
}
```
这样就可以统计出每个系中各个学历的人数,输出格式也更加清晰。
相关问题
在教职工信息管理系统中,使用链表和类,编写一段统计学历人数的代码,应该如何思考并改进优化为统计各系各学历人数的代码?
要统计各系各学历的人数,可以在统计学历人数的基础上,再加上对系别的统计。具体实现方法是,先定义一个包含系别和学历的结构体,然后使用一个map来存储各系各学历的人数。
代码示例:
```cpp
struct DeptEdu {
string department;
string education;
bool operator<(const DeptEdu& other) const {
if (department != other.department) {
return department < other.department;
}
return education < other.education;
}
};
void countDeptEdu() {
map<DeptEdu, int> deptEduCount;
Node* p = head->next;
while (p != nullptr) {
string& department = p->getData().getDepartment();
string& education = p->getData().getEducation();
deptEduCount[{department, education}]++;
p = p->getNext();
}
for (auto& [deptEdu, count] : deptEduCount) {
cout << deptEdu.department << " " << deptEdu.education << ": " << count << endl;
}
}
```
在这里,我们使用了一个自定义的结构体DeptEdu来表示包含系别和学历的信息,并重载了小于号运算符,以便在map中进行排序和查找。同时,我们还使用auto关键字来简化迭代器的声明。
优化修改代码,可以分系进行学历统计,计算各学历的人数:void countEducation() { Node* p = head->next; int bachelorCount = 0, masterCount = 0, doctoralCount = 0; while (p != nullptr) { if (p->data.getEducation() == "本科") { bachelorCount++; } else if (p->data.getEducation() == "硕士") { masterCount++; } else if (p->data.getEducation() == "博士") { doctoralCount++; } p = p->next; } cout << "本科:" << bachelorCount << endl; cout << "硕士:" << masterCount << endl; cout << "博士:" << doctoralCount << endl; }
可以使用一个 map 来记录各个学历对应的人数,然后遍历链表统计即可,这样可以避免大量的 if-else 判断,代码如下:
```c++
void countEducation() {
Node* p = head->next;
map<string, int> educationCount;
while (p != nullptr) {
educationCount[p->data.getEducation()]++;
p = p->next;
}
for (const auto& [education, count] : educationCount) {
cout << education << ":" << count << endl;
}
}
```
这样就可以统计出每个学历对应的人数,并且不需要对每个学历进行判断,代码更加简洁。