[PAT] A1028 List Sorting

(水)

tips

1

cmp比较函数,若是字符串比较,一定要写成return strcmp(char *, char *) >(/</==) 0;
头文件包含string.h。

题目大意

模仿excel表排序功能。

AC代码

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
struct student {
	char id[8];
	char name[10];
	int score;
};
bool cmp1(student a, student b) {
	return strcmp(a.id, b.id) < 0;
}
bool cmp2(student a, student b) {
	if (strcmp(a.name, b.name) == 0) {
		return strcmp(a.id, b.id) < 0;
	}
	else return strcmp(a.name, b.name) < 0;
}
bool cmp3(student a, student b) {
	if (a.score == b.score)
		return strcmp(a.id, b.id) < 0;
	else return a.score < b.score;
}
int main() {
	vector<student>stu;
	int i;
	int n, col;
	scanf("%d%d", &n, &col);
	for (i = 0;i < n;i++) {
		student stutemp;
		scanf("%s", stutemp.id);
		scanf("%s", stutemp.name);
		scanf("%d", &stutemp.score);
		stu.push_back(stutemp);
	}
	if (col == 1) {
		sort(stu.begin(), stu.end(), cmp1);
	}
	if (col == 2) {
		sort(stu.begin(), stu.end(), cmp2);
	}
	if (col == 3) {
		sort(stu.begin(), stu.end(), cmp3);
	}
	for (i = 0;i < n;i++) {
		printf("%s %s %d
", stu[i].id, stu[i].name, stu[i].score);
	}
	return 0;
}

原文地址:https://www.cnblogs.com/yue36/p/12879707.html