文章

34

粉丝

67

获赞

7

访问

8.8k

头像
成绩排序 题解:
P1151 清华大学上机题
发布于2024年2月25日 10:43
阅读数 307

这个题 需要 使用结构体来存储 学生姓名以及分数,还要自己定义排序的规则,sort函数排序时不稳定的,所以可以利用stable_sort函数进行排序,这个函数与sort函数的用法是一样的。

#include <bits/stdc++.h>

using namespace std;

struct student {
  string name;
  int score;
};

bool cmpStudent1(student p, student q) { return p.score > q.score; }
bool cmpStudent2(student p, student q) { return p.score < q.score; }

int main() {
  int n;
  int m;
  while (cin >> n, cin >> m) {
    student p[n];

    // 创建了student 类型的数组
    for (int i = 0; i < n; i++) {

      cin >> p[i].name >> p[i].score;
    }
    if (m == 0) {
      stable_sort(p, p + n, cmpStudent1);
    } else {
      stable_sort(p, p + n, cmpStudent2);
    }

    for (int i = 0; i < n; i++) {
      cout << p[i].name << " " << p[i].score << endl;
      // printf("%s %d\n", p[i].name, p[i].score);
    }
  }

  return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发