當我嘗試使用自定義比較器對成分進行排序時,出現此編譯器錯誤。無法使用自定義比較器函數對列表進行排序
kitchen.cpp: In member function ‘void Kitchen::printContents(std::ofstream&)’:
kitchen.cpp:172: error: no matching function for call to ‘std::list<Ingredient, std::allocator<Ingredient> >::sort(<unresolved overloaded function type>)’
/usr/include/c++/4.2.1/bits/list.tcc:271: note: candidates are: void std::list<_Tp, _Alloc>::sort() [with _Tp = Ingredient, _Alloc = std::allocator<Ingredient>]
/usr/include/c++/4.2.1/bits/list.tcc:348: note: void std::list<_Tp, _Alloc>::sort(_StrictWeakOrdering) [with _StrictWeakOrdering = bool (Kitchen::*)(const Ingredient&, const Ingredient&), _Tp = Ingredient, _Alloc = std::allocator<Ingredient>]
下面是導致它的代碼:
bool sortFunction(const Ingredient a, const Ingredient b)
{
if (a.getQuantity() < b.getQuantity())
return true;
else if (a.getQuantity() == b.getQuantity())
{
if (a.getName() < b.getName()) return true;
else return false;
}
else return false;
}
void Kitchen::printContents(std::ofstream &ostr)
{
ostr << "In the kitchen: " << std::endl;
ingredients.sort(sortFunction);
std::list<Ingredient>::iterator itr;
for (itr = ingredients.begin(); itr != ingredients.end(); ++itr)
{
ostr << std::setw(3) << std::right << itr->getQuantity() << " "
<< itr->getName() << std::endl;
}
}
你怎麼定義排序?錯誤是說你沒有與之相匹配的電話。 – TopGunCoder 2013-02-28 18:21:51
@TopGunCoder:'std :: list'有一個'sort()'函數,它需要一個比較器。 – 2013-02-28 18:25:49
你有沒有其他名字爲'sortFunction'的函數? 'sortFunction'是'Kitchen'的非靜態成員? – 2013-02-28 18:31:19