雖然試圖教我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,對不起。
Item23,第104頁的書「有效STL」說:「(對於關聯容器),你可以不知道是否鍵值或對將作爲第一個參數傳遞,所以你真的需要兩個比較函數進行查找,一個關鍵值首先被傳遞,而其中一個首先被傳遞。「在我嘗試的例子中,這不適用嗎? – user2696565
當編譯器產生一個關於不能將Person轉換爲int的錯誤時,這個項目在我腦海中彈出。這就是爲什麼我最終超負荷CompareWeight。 – user2696565
@InnocentRetard它不適用,'vector'是一個序列容器,而不是一個關聯容器。 – jrok