6-13 函数指针(理科实验班)
6-13 函数指针(理科实验班)
分数 10
作者 何振峰
单位 福州大学
梦山高中现需要将某普通班的最优秀学生调整入理科实验班。为此,将从两个方面考察学生,一是数学和英语两门课的总分;另一个是所有四门课的总分。分别找出两科总分和全科总分的第一名,并从中决定调整人选。
输入将首先输入学生数n, (n为不超过80的正整数);接下来依次输入各位学生的学号,数学、英语、语文、理科综合成绩。学号及四科成绩均为不超过300的正整数。
输出时:第一行输出两科总分第一的学号,第二行输出四科总分第一的学号。 约定在两位学生成绩相同时,优先选择学号较小的学生;各位学生的学号均不相同。
裁判测试程序样例:
#include <iostream>
using namespace std;
const int N=80;
struct Student{
int num;
int score[4];
};
/* 请在这里填写答案 */
int main()
{
int i, j, k, n;
bool s2(const Student &, const Student &);
bool s4(const Student &, const Student &);
Student st[N];
cin>>n;
for(i=0;i<n;i++){
cin>>st[i].num;
for(j=0;j<4;j++) cin>>st[i].score[j];
}
cout<<select(st, n, s2)<<endl;
cout<<select(st, n, s4)<<endl;
}
输入样例:
3
6 148 150 120 252
5 148 150 117 260
7 145 148 128 287
输出样例:
5
7
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
参考代码
bool s2(const Student &a, const Student &b) //为了给select函数返回true或false
{
// 比较数学和英语两门课的总分
int sumA = a.score[0] + a.score[1];
int sumB = b.score[0] + b.score[1];
if (sumA == sumB) return a.num < b.num; // 分数相同,学号小的优先,如果a学号小于b,即a排名前于b,返回true
return sumA > sumB; // 分数高的优先,若a排名前于b,返回true
}
bool s4(const Student &a, const Student &b) //为了给select函数返回true或false
{
// 比较所有四门课的总分
int sumA = a.score[0] + a.score[1] + a.score[2] + a.score[3];
int sumB = b.score[0] + b.score[1] + b.score[2] + b.score[3];
if (sumA == sumB) return a.num < b.num; // 分数相同,学号小的优先,如果a学号小于b,即a排名前于b,返回true
return sumA > sumB; // 分数高的优先,若a排名前于b,返回true
}
int select(Student st[], int n, bool (*compare)(const Student&, const Student&)) {
int idx = 0; // 记录当前最优秀学生的索引
for (int i = 1; i < n; i++) {
if ( compare(st[i], st[idx]) ) //如果st[i]排名前于st[idx],返回ture,更新索引
{
idx = i; // 更新最优秀学生的索引
}
}
return st[idx].num; // 返回最优秀学生的学号
}
函数指针知识
在C++中,函数指针是一种特殊的指针,它指向函数而不是变量。函数指针可以用于调用函数,也可以作为参数传递给其他函数。这在实现回调函数或策略模式时非常有用。
bool (*compare)(const Student&, const Student&)是一个函数指针的声明。让我们分解这个声明以更好地理解它:
bool 表示这个函数返回一个布尔值(true 或 false)。
(*compare) 是函数指针的名称,即 compare。括号(*) 表明这是一个指针。
(const Student&, const Student&) 表示这个函数接受两个参数,每个参数都是对 Student 类型对象的常量引用。使用常量引用(const T& ,T表示所引用对象的类型)可以避免复制大型对象,并确保函数不会修改这些对象。
整个表达式 bool (*compare)(const Student&, const Student&) 声明了一个名为 compare 的函数指针,它指向一个接受两个 Student 类型的常量引用作为参数,并返回布尔值的函数。
在上下文中,这种函数指针用于比较两个 Student 对象。例如,你可以定义多个比较函数(比如按照两科总分比较、四科总分比较等),然后根据需要将这些函数的地址作为参数传递给 select 函数。select 函数通过调用传递给它的比较函数来决定哪个 Student 对象是“最优”的。
这种方式提供了极大的灵活性,因为你可以在不改变 select 函数实现的情况下,通过传递不同的比较函数来改变选择标准。这是一种实现多态行为的技巧,允许在运行时决定使用哪个函数。
浙公网安备 33010602011771号