2013-02-09 89 views
3

幫助我不明白爲什麼我不能運行這段代碼它是一個家庭作業分配和xCode似乎不同意我時,它說我沒有定義的功能。看到波紋管在主要的錯誤「沒有匹配的函數調用」模板C++

template <class Comparable> 
Comparable maxSubsequenceSum1(const vector<Comparable> & a, int & seqStart, int & seqEnd){ 
     int n = a.size(); 
     Comparable maxSum = 0; 

     for(int i = 0; i < n; i++) 
      for(int j = i; j < n; j++) 
      { 
       Comparable thisSum = 0; 
       for(int k = i; k <= j; k++) 
        thisSum += a[ k ]; 

       if(thisSum > maxSum) 
       { 
        maxSum = thisSum; 
        seqStart = i; 
        seqEnd = j; 
       } 
      } 

     return maxSum; 

} 



int main(){ 


     vector<int> vectorofints; 
     vectorofints.resize(128); 
     for (int i=0; i<vectorofints.size(); i++){ 
      vectorofints[i] = (rand() % 2001) - 1000; 
     } 
     maxSubsequenceSum1(vectorofints, 0, 127) //**---->the error i get in xcode is "No matching function for call to maxSubsequenceSum1" 

     return 0; 
} 
+0

你缺少「詮釋與seqEnd」後一個右括號。它是一個錯字還是它在你的代碼中的錯誤? – 2013-02-09 23:30:10

+0

是的,這是一個錯字,讓我修復 – 2013-02-09 23:31:51

+0

我已經爲你發佈了一個解決方案。看看是否修復它。 – 2013-02-09 23:36:35

回答

2

更改簽名從

Comparable maxSubsequenceSum1(const vector<Comparable> & a, 
           int & seqStart, int & seqEnd) 

Comparable maxSubsequenceSum1(const vector<Comparable> & a, 
           int seqStart, int seqEnd) 

同樣的問題發生,如果你會做int & i = 0;。你不能從右值初始化非const引用。 0127是在表達式末尾過期的臨時對象,臨時對象不能綁定到非常量引用。

+0

哇謝謝我的教授實際上寫了那部分,所以我認爲我沒有理由懷疑它,這是我正在做的事 – 2013-02-09 23:37:52

+0

另一個解決方法它傳遞一個左值,即'int x = 0;'然後傳遞'x'代替。但是,對於內置類型的引用是沒有意義的,你應該告訴你的教授簽名應該改變。 – 2013-02-09 23:39:20

+0

@JonathanBuzaglo你會驚訝地發現有多少不好的東西試圖被教給C++:( – 2013-02-10 00:03:58

0

編譯器是正確的。您正在呼叫maxSubsequenceSum1(std::vector<int>&, int, int),你定義maxSubsequenceSum1(std::vector<int>&, int &, int &)

有2個快速解決方案:

1)重新定義你的函數不採取一個參考。
2)將你的常量移動到變量上,並按照這種方式傳遞它們。

注意:您的代碼存在另一個問題。您調用函數maxSubsequenceSum1,但不告訴它要使用的模板參數。

我已糾正,糾正是正確的。該筆記無效。

+2

'但你不告訴它要使用什麼樣的模板參數。「這不是一個可以推導出來的問題。 – 2013-02-09 23:38:17

+0

@JesseGood你謝謝 – 2013-02-09 23:41:07

+0

謝謝修復它 – 2013-02-09 23:42:20

0

您已經聲明瞭一個函數,該函數需要兩個整數引用,但是您調用的函數會按值取兩個整數。 它應該是這樣的

vector<int> vectorofints; 
     vectorofints.resize(128); 
     for (int i=0; i<vectorofints.size(); i++){ 
      vectorofints[i] = (rand() % 2001) - 1000; 
     } 
     int k = 0; 
     int j = 127; 
     maxSubsequenceSum1(vectorofints, k, j) 

     return 0; 
+1

謝謝修復它 – 2013-02-09 23:39:25

+0

@ M.Alem你沒有解釋爲什麼他應該改變代碼還有,這是一個很糟糕的解決方案 – 2013-02-10 00:03:18