c++五位学生对象成绩排序降序
时间: 2023-09-20 20:07:05 浏览: 35
可以使用结构体来保存每个学生的信息,包括姓名和成绩。然后使用标准库中的`sort`函数进行排序,最后按照降序输出排序后的结果。
以下是示例代码:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Student {
string name;
int score;
};
bool cmp(Student a, Student b) {
return a.score > b.score; // 降序排序
}
int main() {
const int N = 5;
Student students[N] = {{"Alice", 80}, {"Bob", 90}, {"Charlie", 70}, {"David", 85}, {"Eve", 75}};
sort(students, students + N, cmp);
for (int i = 0; i < N; i++) {
cout << students[i].name << " " << students[i].score << endl;
}
return 0;
}
```
输出结果为:
```
Bob 90
David 85
Alice 80
Eve 75
Charlie 70
```
相关问题
学生类Student成员:id,yw,sx,sum,定于5位学生对象,对学生对象降序排序,编写“<”运算符函数,用于比较两个对象的大小
以下是实现上述需求的示例代码:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
class Student {
public:
int id; // 学号
int yw; // 语文成绩
int sx; // 数学成绩
int sum; // 总成绩
// 构造函数
Student(int id, int yw, int sx) {
this->id = id;
this->yw = yw;
this->sx = sx;
this->sum = yw + sx;
}
// < 运算符函数
bool operator<(const Student& other) const {
return sum > other.sum;
}
};
int main() {
Student s1(1001, 80, 90);
Student s2(1002, 85, 95);
Student s3(1003, 90, 85);
Student s4(1004, 95, 90);
Student s5(1005, 85, 80);
Student students[] = {s1, s2, s3, s4, s5};
sort(students, students + 5);
for (int i = 0; i < 5; i++) {
cout << "学号:" << students[i].id << ",总成绩:" << students[i].sum << endl;
}
return 0;
}
```
运行结果为:
```
学号:1004,总成绩:185
学号:1002,总成绩:180
学号:1003,总成绩:175
学号:1001,总成绩:170
学号:1005,总成绩:165
```
在上述代码中,定义了一个名为 Student 的类,该类包含 4 个成员变量,分别是学号(id)、语文成绩(yw)、数学成绩(sx)和总成绩(sum)。在构造函数中,会根据语文成绩和数学成绩计算总成绩。
为了实现对学生对象的降序排序,我们在类中重载了 `<` 运算符函数,该函数比较两个学生对象的总成绩大小,如果第一个学生对象的总成绩大于第二个学生对象的总成绩,则返回 true,否则返回 false。
在主函数中,我们定义了 5 个学生对象,并将它们存储在一个数组中。然后使用 `sort` 函数对该数组进行排序,由于我们已经在类中重载了 `<` 运算符函数,所以 `sort` 函数会自动调用该函数进行比较。
最后,我们遍历排序后的数组,并输出每个学生对象的学号和总成绩。
用c++做输入5名学生考试成绩, 然后降序排序,最后输出。 示例: 输入: 10 50 40 90 60 输出: 90 60 50 40 10
好的,以下是 C++ 的代码实现:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
const int N = 5; // 学生人数
int scores[N];
// 读取学生成绩
for (int i = 0; i < N; i++) {
cin >> scores[i];
}
// 降序排序
sort(scores, scores + N, greater<int>());
// 输出学生成绩
for (int i = 0; i < N; i++) {
cout << scores[i] << " ";
}
cout << endl;
return 0;
}
```
在这个程序中,我们使用了 STL 中的 `sort()` 函数对学生成绩进行降序排序。`sort()` 函数的第一个参数是要排序的数组的起始地址,第二个参数是要排序的数组的终止地址的下一个地址(即超出数组范围的一个地址),第三个参数是一个比较函数,用于指定排序规则。在本例中,我们使用了 `greater<int>()` 函数对象,它表示使用降序排序。最后,我们使用一个循环输出排序后的学生成绩。
您可以按照以下格式输入学生成绩:
```
10 50 40 90 60
```
运行程序后,您将得到如下输出:
```
90 60 50 40 10
```