#include <iostream>#include <algorithm>using namespace std;class Student {public: int id; int yw; int sx; int sum; Student(int i, int y, int s) : id(i), yw(y), sx(s), sum(y + s) {} bool operator<(const Student &other) const { return sum > other.sum; }};int main() { Student s[5] = {Student(1001, 80, 80), Student(1002, 70, 70), Student(1003, 90, 90), Student(1004, 50, 50), Student(1005, 60, 60)}; sort(s, s + 5); for (int i = 0; i < 5; i++) { cout << "id: " << s[i].id << ", yw: " << s[i].yw << ", sx: " << s[i].sx << ", sum: " << s[i].sum << endl; } return 0;}冒泡排序代替
时间: 2023-12-18 17:05:38 浏览: 65
可以使用冒泡排序代替sort函数进行排序,如下所示:
```c++
#include <iostream>
using namespace std;
class Student {
public:
int id;
int yw;
int sx;
int sum;
Student(int i, int y, int s) : id(i), yw(y), sx(s), sum(y + s) {}
bool operator<(const Student &other) const {
return sum > other.sum;
}
};
int main() {
Student s[5] = {Student(1001, 80, 80), Student(1002, 70, 70),
Student(1003, 90, 90), Student(1004, 50, 50),
Student(1005, 60, 60)};
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4 - i; j++) {
if (s[j].sum < s[j+1].sum) {
swap(s[j], s[j+1]);
}
}
}
for (int i = 0; i < 5; i++) {
cout << "id: " << s[i].id << ", yw: " << s[i].yw << ", sx: " << s[i].sx << ", sum: " << s[i].sum << endl;
}
return 0;
}
```
这里使用了一个嵌套循环,外层循环控制比较的轮数,内层循环进行相邻元素的比较和交换。每轮循环都将当前最大值移动到数组末尾。
阅读全文
相关推荐















