分析这个代码,判断是否有错误void calcRank(vector<Student>& students) { sort(students.begin(), students.end(), compareStudents); for (int i = 0; i < students.size(); i++) { if (i == 0 || students[i].score != students[i - 1].score) { students[i].schRank = i + 1; } else { students[i].schRank = students[i - 1].schRank; } } map<string, vector<Student>> clsMap; for (Student s : students) { clsMap[s.cls].push_back(s); } for (auto& p : clsMap) { auto& clsStudents = p.second; sort(clsStudents.begin(), clsStudents.end(), compareStudents); for (int i = 0; i < clsStudents.size(); i++) { if (i == 0 || clsStudents[i].score != clsStudents[i - 1].score) { clsStudents[i].clsRank = i + 1; } else { clsStudents[i].clsRank = clsStudents[i - 1].clsRank; } } } }为什么这个班级排名都是0
时间: 2024-03-23 12:41:31 浏览: 20
这段代码中的班级排名是由 clsRank 变量维护的,但是在代码中并没有给 clsRank 变量进行初始化,导致所有学生的班级排名都为0。
解决方法是在定义 Student 结构体时,将 clsRank 初始值设为0,即:
```
struct Student {
string name;
string cls;
int score;
int schRank = 0; // 添加默认值
int clsRank = 0; // 添加默认值
};
```
或者在 calcRank() 函数中,在对 clsStudents 进行排名之前,将 clsStudents 中所有学生的 clsRank 值初始化为0,即:
```
for (auto& p : clsMap) {
auto& clsStudents = p.second;
for (auto& s : clsStudents) { // 添加循环
s.clsRank = 0;
}
sort(clsStudents.begin(), clsStudents.end(), compareStudents);
for (int i = 0; i < clsStudents.size(); i++) {
if (i == 0 || clsStudents[i].score != clsStudents[i - 1].score) {
clsStudents[i].clsRank = i + 1;
} else {
clsStudents[i].clsRank = clsStudents[i - 1].clsRank;
}
}
}
```
这样就可以保证班级排名的正确性了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)