【PAT甲级】1028 List Sorting (25分)

解题过程的小记录,如有错误欢迎指出。

难度:半星(极度简单题

题目分析

分别按照学生的学号、名字和成绩进行排序

注意点

我的解题过程

思路

利用结构体输入学生信息,按照指定的排序选择对应排序函数,最后进行输出

bug

  1. 中途有想过在compare函数中增加一个参数值,然后写到一半发现sort里的compare函数的引用不加参数值,改成在主函数里面进行选择的代码量和在函数中差不多
  2. 刚开始习惯性的把成绩从高到低排序,在对照样例代码的时候进行了修改

代码

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>

using namespace std;

struct student {
	string ID;
	string name;
	int grade;
};

int comp1(student s1,student s2) {
	return s1.ID < s2.ID;
}

int comp2(student s1, student s2) {
	return s1.name == s2.name ? s1.ID < s2.ID : s1.name < s2.name;
}

int comp3(student s1, student s2) {
	return s1.grade == s2.grade ? s1.ID<s2.ID : s1.grade<s2.grade;
}

int main()
{
	int N, C;
	cin >> N >> C;
	vector<student> stu(N);
	for (int i = 0; i < N; i++) {
		cin >> stu[i].ID >> stu[i].name >> stu[i].grade;
	}
	switch (C)
	{
	case 1:sort(stu.begin(), stu.end(), comp1); break;
	case 2:sort(stu.begin(), stu.end(), comp2); break;
	case 3:sort(stu.begin(), stu.end(), comp3); break;
	}
	for (int i = 0; i < N; i++) {
		printf("%s %s %d\n", stu[i].ID.c_str(), stu[i].name.c_str(), stu[i].grade);
	}
    return 0;
}

dalao的代码

全部代码因版权原因不放出来,大家可以自行去柳神博客购买或者参考晴神的上机笔记~

借鉴点

  1. 如果只写一个比较函数的话可以采用将C设置为全局变量的方法,这样就可以在函数中即使不设置参数也可以进行读取(机智啊~~)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值