您的位置:首页 > 其它

学生结构体数组,按成绩排序、按年 龄排序,按名字排序...如何实现?

2014-03-18 14:43 645 查看
#include <stdio.h>

//学生结构体数组,按成绩排序、按年龄排序,按名字排序...如何实现?

//1. 动态排序

typedef struct student {

char name[20]; //注意类型不可为
char * name 否则为常量 即不可改变
int age;
float score;
}Student;

typedefBOOL(*pFun)(Student *,Student
*);
BOOL sortWithScore(Student *stu1,Student *stu2) {
return stu1->score < stu2->score;
}

BOOL sortWithName(Student *stu1,Student *stu2) {
returnstrcmp(stu1->name, stu2->name)
>0;
}

BOOL sortWithAge(Student *stu1,Student *stu2) {
return stu1->age < stu2->age;
}

void bubbleSort(Student * str,int count,pFun
p) {
for (int i =0; i < count -1; i++)
{
for (int j =0; j < count - i -1;
j++) {
if (p(&str[j],&str[j +1])) {
Student temp = str[j]; //结构体名代表的是结构体整体,可直接赋值
str[j] = str[j +1]; //而数组名代表的是首地址,所以不能
str[j +1] = temp;
}
}
}
}

void printStudent(Student * str,int count) {
for (int i =0; i < count; i++) {
printf("%-10s,%-3d,%-5.2f",str[i].name,str[i].age,str[i].score);
printf("\n");
}
}

int main(int argc,constchar * argv[])
{

Student stu[5] = {{"wangxiao",23,79},{"yanyuan",21,89},{"liujian",19,95},{"daomeicui",24,59.9},{"haha",20,69}};

// bubbleSort(stu, 5,sortWithName); //按姓名排序

// bubbleSort(stu, 5, sortWithAge); //按年龄

bubbleSort(stu,5,sortWithScore); //按成绩
printStudent(stu,5);

return0;
}

//2. 函数指针数组(回调函数)

#include <stdio.h>

typedef struct student {

char name[20]; //注意类型不可为
char * name 否则为常量
即不可改变
int age;
float score;
}Student;

//重定义函数指针,新类型名为pCompair
typedefBOOL(*pCompair)(Student *,Student
*);

typedefstruct functionPointer {
char sortWayName[50];
pCompair pointer; //按什么方式排序的指针
}fPointer;

BOOL sortWithScore(Student *stu1,Student *stu2) {
return stu1->score < stu2->score;
}
BOOL sortWithName(Student *stu1,Student *stu2) {
returnstrcmp(stu1->name, stu2->name)
>0;
}
BOOL sortWithAge(Student *stu1,Student *stu2) {
return stu1->age < stu2->age;
}

//获得排序方式的函数指针
pCompair getFunction(fPointer * str,int count,char
* arr) {

//遍历数组,判断用哪个函数作为返回值
for (int i =0; i < count; i++) {
if (strcmp(str[i].sortWayName, arr) ==0)
{
return str[i].pointer;
}
}

return
NULL;
}

void bubbleSort(Student * str,fPointer *fpointer,int
count,char * arr) {
pCompair p =getFunction(fpointer,3, arr);
for (int i =0; i < count -1; i++)
{
for (int j =0; j < count - i -1;
j++) {
if (p(&str[j],&str[j +1])) {
Student temp = str[j]; //结构体名代表的是结构体整体,可直接赋值
str[j] = str[j +1]; //而数组名代表的是首地址,所以不能
str[j +1] = temp;
}
}
}
}

//输出结构体
void printStudent(Student * str,int count) {
for (int i =0; i < count; i++) {
printf("%-10s,%-3d,%-5.2f",str[i].name,str[i].age,str[i].score);
printf("\n");
}
}

int main(int argc,constchar * argv[])
{
fPointer pointer[3] = {{"姓名排序",sortWithName},{"年龄排序",sortWithAge},{"成绩排序",sortWithScore}};

Student stu[5] = {{"wangxiao",23,79},{"yanyuan",21,89},{"liujian",19,95},{"daomeicui",24,59.9},{"haha",20,69}};

bubbleSort(stu,pointer,5,"成绩排序");

printStudent(stu,5);

return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐