我在加速C++中練習時遇到問題。 的主要功能如下:加速的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);
}
但它不起作用。 任何人都可以提供幫助嗎?
您可以通過縮進四個空格來正確地格式化您的代碼。 – 2011-01-28 20:29:41
將來,請通過突出顯示這些代碼片段並按Ctrl + K或在編輯器中點擊「{}」按鈕來格式化代碼片段。 – birryree 2011-01-28 20:30:05