考察结构体排序
#include<iostream>
#include<algorithm>
#include<vector>
#include<string.h>
typedef struct Student
{
int id;
char name[20];
int g;
}Student;
int C;
bool cmp(Student a, Student b)
{
if(C == 1)
return a.id < b.id;
else if(C == 2)
{
if( strcmp(a.name, b.name) == 0 )
return a.id < b.id;
else return strcmp(a.name, b.name)<0;
}
else if(C == 3)
{
if(a.g == b.g)
return a.id < b.id;
else return a.g < b.g;
}
}
int main()
{
int N;
while( scanf("%d%d", &N, &C) != EOF )
{
std::vector<Student> stuVec(N);
for(int i = 0; i < N; ++i)
scanf("%d%s%d", &stuVec[i].id, stuVec[i].name, &stuVec[i].g);
//sort
std::sort(stuVec.begin(), stuVec.end(), cmp);
for(int i = 0; i < N; ++i)
printf("%06d %s %d\n", stuVec[i].id, stuVec[i].name, stuVec[i].g);
}
return 0;
}

本文介绍了一个使用C++实现的结构体排序程序实例。该程序定义了一个包含学生ID、姓名及成绩的结构体,并实现了根据不同条件(如ID、姓名或成绩)对学生数据进行排序的功能。通过这个例子,读者可以了解如何在C++中定义结构体类型、使用标准库函数进行排序以及自定义比较函数。
1921

被折叠的 条评论
为什么被折叠?



