2011-01-28 31 views
0

我在加速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); 

} 

但它不起作用。 任何人都可以提供幫助嗎?

+0

您可以通過縮進四個空格來正確地格式化您的代碼。 – 2011-01-28 20:29:41

+0

將來,請通過突出顯示這些代碼片段並按Ctrl + K或在編輯器中點擊「{}」按鈕來格式化代碼片段。 – birryree 2011-01-28 20:30:05

回答

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(); 
} 

這會給你每個學生的平均水平,但從你的問題來看,你不清楚究竟需要什麼樣的輸出。

0

參數您analysis功能是一個學生,不是他們的vector這是你傳遞什麼。

我覺得你的分析功能應該接受學生的vector,遍歷各一個,併爲每個學生撥打optimistic_median

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) 

一個問題是,在這裏你試圖將一個函數作爲參數傳遞給一個函數。你不能這麼做 - 你可以傳遞一個指向函數的指針,但不是實際的函數。

-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); 
}