无法使用自定义比较器功能对列表进行排序

Can't sort list with custom comparator function

本文关键字:列表 排序 功能 比较器 自定义      更新时间:2023-10-16

当我尝试用自定义比较器对成分进行排序时,我得到了这个编译器错误。

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

可能在某个地方(例如在Kitchen中)存在另一个sortFunction,从而导致上述错误。

ingredients.sort(::sortFunction);

和这个问题类似。

另外,为了更好的编码实践,您可能希望更改

bool sortFunction(const Ingredient a, const Ingredient b)

bool sortFunction(const Ingredient &a, const Ingredient &b)

第一个传入对象的副本,第二个传入对象的引用。

看起来你在kitthen中有一个叫做sortFunction的方法,编译器不能选择合适的一个。你可以试试:

list.sort( ::sortFunction );

要解决这个问题,或者如果你提供的函数假设是Kitchen类的方法,你需要修复它。

顺便说一句:

if (a.getName() < b.getName()) return true;
else return false;

等于:

return a.getName() < b.getName();

我猜你声明了一个成员函数Kitchen::sortFunction。在另一个成员函数(如printContents)中,这将隐藏您想要使用的非成员函数。

错误消息提示是这种情况;它正在尝试实例化sort的成员函数类型bool (Kitchen::*)(const Ingredient&, const Ingredient&)

如果成员函数不应该存在,则删除声明。如果是,则重命名其中一个函数,或者将非成员函数引用为::sortFunction

你的排序函数是:

bool sortFunction(const Ingredient a, const Ingredient b)

但应该是:

bool sortFunction(const Ingredient &a, const Ingredient &b)

(注意参考文献)

同样,正如已经提到的,您的Kitchen类已经有一个名为sortFunction()的函数,并且它具有优先级,因此要么使用::sortFunction(),要么为每个函数提供一个唯一且更具描述性的名称。

如果Kitchen::sortFunction() 是你想要的,它需要是一个静态成员函数