130 likes | 259 Views
七 、结构体与链表(二). 7.1 结构体概述 7.2 结构体类型声明 7.3 结构体变量的定义、使用、初始化 7.4 结构体数组及其应用 7.5 结构体和指针 7.6 链表概述 7.7 创建和操作链表. 7.4 结构体数组及其应用. 数组的每个元素都是结构类型的数据,它们分别包含各个成员项。 1 、 结构数组的定义. struct Student { int sno; double score; }; Student st[30];. struct Student { int sno;
E N D
七 、结构体与链表(二) 7.1 结构体概述 7.2 结构体类型声明 7.3 结构体变量的定义、使用、初始化 7.4 结构体数组及其应用 7.5 结构体和指针 7.6 链表概述 7.7 创建和操作链表
7.4 结构体数组及其应用 数组的每个元素都是结构类型的数据,它们分别包含各个成员项。 1、 结构数组的定义 struct Student { int sno; double score; }; Student st[30]; struct Student { int sno; double score; } st[30]; struct { int sno; double score; } st[30];
2、 结构体数组的初始化 Studentst[2]={ {1001,89.0}, {1002,76.0} }
3、结构体数组应用举例1 输入n个学生的姓名和3门功课成绩,然后根据3门功课的平均成绩从高分到低分显示每个学生的姓名、3门功课成绩及平均成绩。 struct Stud { string sname; double score1, score2, score3; }; bool cmp(Stud s1, Stud s2) { int total1 = s1.score1+s1.score2+s1.score3; int total2 = s2.score1+s2.score2+s2.score3; return total1 > total2; }
Stud st[100]; cin>>n; // n<=100 for(int i=0; i<n; i++) { cin>>st[i].sname>>st[i].score1 >>st[i].score2 >>st[i].score3; } // 调用前面已经实现的排序函数,mySort里面使用cmp函数进行比较 mySort(st, n); for(int i=0; i<n; i++) { cout<<st[i].sname << st[i].score1 << st[i].score2 << st[i].score3 <<(st[i].score1+ st[i].score2+ st[i].score3)/3<<endl; } 尝试用结构体完成1129,1199
结构体数组应用举例2 实现每周一次的在线解题排行榜 输入数据: 包括每个人的上期完成数,本期Normal,本期Special数量 排名规则: 1)先按normal排序,取前10人 2)再排本期完成数量最多的5人(出现在规则1中的人不参于这里的排序) 3)对剩余的人员按total排序
(1) 如何构造结构体 struct Stud { string id; // 账号 string name; // 姓名 int last; // 上期总数 int normal; // 标准解题数 int special; // 特殊解题数 int total; // 本期总数 int complete; // 本期完成 int rank; // 排名 }; Stud st[50];
(2) 成功排序后如何确定名次 for(int i=0; i<len; i++) { if (i>0 && st[i].normal==st[i-1].normal) { st[i].rank=st[i-1].rank; } else { st[i].rank=i+1; } }
(4) 如何排序(可用选择排序) int A[N]; // 循环N-1轮次,第i轮选出第i小的元素,并与第i个元素交换 for( int i=0; i<N-1; i++) { //第i轮选出第i小的元素 int pos = i; for( int j=i+1; j<N; j++) { if(A[j]<A[pos]) pos=j; } // 交换元素,使得第i轮后,第i小的元素落在正确的位置(第i位置) int t=A[i]; A[i]=A[pos]; A[pos]=t; } if(cmp(A[j] , A[pos]) == true) pos=j;
(5) 如何使用排序规则 bool cmpByNormal(Stud s1, Stud s2) { if(s1.normal==s2.normal) { return s1.total>s2.total; } else { return s1.normal>s2.normal; } } 分析这里的排序策略和前面的规则1)有何微小的差异?
(6) 实现整个程序 // 输入数据 // 处理数据 mySort(stud,n,0); // process1 mySort(stud+10,n-10,1); // process2 mySort(stud+15,n-15,2); // process3 rankByNomal(stud,10,1); // process4 rankByComplete(stud+10,5,11); // process5 rankByTotal(stud+15,n-15,16); // process6 //输出结果
课后练习(要求用结构体完成) • 请登陆在线练习系统http://acmoj.net • 完成如下练习: 必做 选做 1062 最短距离的两点 1116 竞赛排名 1129 成绩排名 1204 足球联赛排名 1420 获奖 1355 Clay Bully 1046 EXCEL排序 1211 确定最终排名 1245 节约有理 1354 Grandpa is Famous