我在使用Accelerated C ++时遇到了问题。 主要功能如下:
int main()
{
// students who did and didn't do all their homework
vector<Student_info> did, didnt;
// read the student records and partition them
Student_info student;
while (read(cin, student)) {
if (did_all_hw(student))
did.push_back(student);
else
didnt.push_back(student);
}
// verify that the analyses will show us something
if (did.empty()) {
cout << "No student did all the homework!" << endl;
return 1;
}
if (didnt.empty()) {
cout << "Every student did all the homework!" << endl;
return 1;
}
// do the analyses
write_analysis(cout, "median", median_analysis, did, didnt);
write_analysis(cout, "average", average_analysis, did, didnt);
write_analysis(cout, "median of homework turned in",
optimistic_median_analysis, did, didnt);
return 0;
}
函数write_analysis有5个参数,其中第三个是分析函数。
写分析如下:
void write_analysis(ostream& out, const string& name,
double analysis(const vector<Student_info>&),
const vector<Student_info>& did,
const vector<Student_info>& didnt)
{
out << name << ": median(did) = " << analysis(did) <<
", median(didnt) = " << analysis(didnt) << endl;
}
这个问题要求读者写一个分析函数来调用optimistic_median,乐观中位数是:
double optimistic_median(const Student_info& s)
{
vector<double> nonzero;
remove_copy(s.homework.begin(), s.homework.end(),
back_inserter(nonzero), 0);
if (nonzero.empty())
return grade(s.midterm, s.final, 0);
else
return grade(s.midterm, s.final, median(nonzero));
}
然后,大概可以让write_analysis函数工作,这对我来说似乎没有。 我试过了
double analysis(const Student_info& s)
{
optimistic_median(s);
}
但它不起作用。 有人能帮忙吗?
答案 0 :(得分:0)
analysis
函数的参数是单个学生,而不是vector
他们正在传递的内容。
我认为您的分析功能应接受vector
个学生,对每个学生进行迭代,并为每个学生致电optimistic_median
。
答案 1 :(得分:0)
void write_analysis(ostream& out, const string& name,
double analysis(const vector<Student_info>&),
const vector<Student_info>& did,
const vector<Student_info>& didnt)
一个问题是,您在尝试将函数作为参数传递给函数。你不能这样做 - 你可以将指针传递给函数,但不能传递给实际函数。
答案 2 :(得分:0)
首先,您需要为分析函数使用适当的名称。那将是optimistic_median_analysis
。接下来,您必须接受对向量的引用,迭代每个项目并将optimistic_median
函数应用于它。
double optimistic_median_analysis(const vector<Student_info> &v)
{
return std::accumulate(v.begin(), v.end(), 0.0, optimistic_median) / v.size();
}
这会给你每个学生的平均值,但是你的问题不清楚究竟是什么输出需要。
答案 3 :(得分:-1)
我正在练习,这是正确的答案。如本书第110页所述,我们必须“报告每组的中位数”,即。乐观的中间人群。
double optimistic_median_analysis (const vector<Student_info> &s) {
vector<double> optgrades;
transform(s.begin(), s.end(), back_inserter(optgrades), optimistic_median);
return median(optgrades);
}