一、概述
根据不同列将记录按序输出。
极简单的一道题,在做了那么多恶心的排序题之后看到这道题简直要哭出来。唯一要注意的是很有趣的一点,也是我遇到的bug,将在下文说明。
二、分析
以结构体储存记录。如下:
struct Student
{
char ID[6];
int grade;
char name[9];
}stu[100000];
而不能是
struct Student
{
char ID[6];
char name[9];
int grade;
}stu[100000];
原因如下:
当我们最后输出时,使用的是%s,printf使用%s时,不遇到空格、\0等是不会停止的,这样,如果我们把两个char数组相邻放在结构体中,那么在内存中,两个char数组也是相邻的,那么,当我用scanf输出ID时,由于ID与name相邻,ID尾部既没有空格也没有\0,于是会将后面的name也输出,这样输出是错误的。因此,把int形式的grade放在中间,就可以破坏它们在内存中的相邻性,也就阻止了这种情况。其他的就没有什么好说的了。
三、总结
结构体中的字符串要分开存放,或者初始化时末尾加一个\0。
PS:代码如下:
#include<stdio.h>
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
struct Student
{
char ID[6];
int grade;
char name[9];
}stu[100000];
bool cmp1(Student a, Student b)
{
int s = strcmp(a.ID, b.ID);
return s < 0;
}
bool cmp2(Student a, Student b)
{
int s = strcmp(a.name, b.name);
int _s = strcmp(a.ID, b.ID);
if(s!=0)
return s < 0;
else
return _s < 0;
}
bool cmp3(Student a, Student b)
{
int _s = strcmp(a.ID, b.ID);
if (a.grade != b.grade)
return a.grade < b.grade;
else
return _s < 0;
}
int main()
{
int N, C;
scanf("%d %d", &N, &C);
int i;
for (i = 0; i < N; i++)
{
scanf("%s %s %d", &stu[i].ID, &stu[i].name, &stu[i].grade);
}
switch (C)
{
case 1:
sort(stu, stu + N, cmp1);
break;
case 2:
sort(stu, stu + N, cmp2);
break;
case 3:
sort(stu, stu + N, cmp3);
break;
}
for (i = 0; i < N; i++)
printf("%s %s %d\n", stu[i].ID, stu[i].name, stu[i].grade);
}