优化修改代码,分别按照“系”进行学历统计,分别计算每个系中各学历的人数: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 14:04:57 浏览: 74
统计字符串中字母和数字个数
可以使用一个嵌套的 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;
}
}
```
这样就可以统计出每个系中各个学历的人数,输出格式也更加清晰。
阅读全文