2013-08-22 30 views
1

雖然試圖教我STL,我寫了下面的類:LOWER_BOUND拋出「錯誤C2914:‘的std :: LOWER_BOUND’:不能推導出模板參數的函數參數不明確」

class Person{ 
public: 
    ... 
    bool operator<(const Person& p) const; // sorts by weight 
    friend bool compareWeight(const Person &p, const int& wt); //true if wt<p.weight 
    friend bool compareWeight(const int& wt, const Person &p); 
    ... 
private: 
    int age; 
    int weight; 
}; 

操作<定義如:

bool Person::operator<(const Person& p) const{ 
    if (weight<p.weight) 
     return true; 
    else 
     return false; 
} 

爲什麼不這項工作:

// get lower_bound for weight = 50 
vector<Person>::iterator itr = lower_bound(v.begin(),v.end(),50,compareWeight); 

它拋出:

error C2914: 'std::lower_bound':cannot deduce template argument as function argument is ambiguous 

我可以在此使用虛擬人,具有重量= 50,然後調用LOWER_BOUND解決:

vector<Person>::iterator itr = lower_bound(v.begin(),v.end(), dummy); 

但它顯然不是很優雅,有人可以幫我獲得compareWeight工作?此外,在這種情況下任何有關最佳方法的建議都會很好。請勿使用Boost或C++ 11,對不起。

回答

1

除了提供兩個朋友函數,您可以提供一個函數對象來執行這兩個操作。

struct CompareWeight { 
    bool operator()(const Person&, int) const; 
    bool operator()(int, const Person&) const; 
}; 

然後就可以調用算法爲:

std::lower_bound(std::begin(v), std::end(v), CompareWeight()); 

注:我同意應該只需要一個超負荷羅,但似乎你的實現(不必完全符合標準)需要另一個方向,如果是這種情況,這提供了一個簡單的解決方法。

+0

Item23,第104頁的書「有效STL」說:「(對於關聯容器),你可以不知道是否鍵值或對將作爲第一個參數傳遞,所以你真的需要兩個比較函數進行查找,一個關鍵值首先被傳遞,而其中一個首先被傳遞。「在我嘗試的例子中,這不適用嗎? – user2696565

+0

當編譯器產生一個關於不能將Person轉換爲int的錯誤時,這個項目在我腦海中彈出。這就是爲什麼我最終超負荷CompareWeight。 – user2696565

+0

@InnocentRetard它不適用,'vector'是一個序列容器,而不是一個關聯容器。 – jrok

1

編譯器需要知道函數的確切簽名以推導出最後一個參數lower_bound。但由於compareWeight超載,它不能決定採取哪一個。因此,你需要manualy投給正確的函數指針:

typedef bool(*Comp)(const Person&, const int&); 
lower_bound(v.begin(),v.end(),50,static_cast<Comp>(&compareWeight)); 

本人來說,我願意做你的虛擬參數做了什麼。


偏題建議:按值傳遞基元類型,速度更快。

friend bool compareWeight(const Person &p, int wt); 
+0

謝謝您的回覆。在嘗試你的建議時出現以下錯誤:「error C2664:'bool(const Person&,const int&)':無法將參數2從'Person'轉換爲'const int&'」事實上,擺脫這個錯誤是爲什麼我首先重載了compareWeight。 – user2696565

+0

@InnocentRetard是存儲'Person'還是'int'的向量?比較器的第一個參數類型必須與容器中的類型匹配,第二個參數類型的第三個參數類型爲'lower_bound'。 – jrok

+0

它的矢量。 – user2696565