无法使用自定义比较器功能对列表进行排序
Can't sort list with custom comparator function
当我尝试用自定义比较器对成分进行排序时,我得到了这个编译器错误。
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() 是你想要的,它需要是一个静态成员函数
相关文章:
- 试图在c++中对数字列表进行排序
- 在STL - C++中按成绩对学生列表进行排序?
- 使用列表 STL 递归进行插入排序
- 列表 iter 不取消引用 使用列表进行插入排序
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 如何按键对 std::对列表进行排序?
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 使用自定义比较函数在类内进行列表排序
- 列表::排序更改值C
- 对于列表排序,有没有办法使用相同的参数让多个运算符重载?
- 在 c++ 中将数字从列表排序到数组中的气泡排序问题
- 运算符<用于列表排序
- C++列表排序功能
- C++ STL 算法(列表排序)OpenMP/多线程实现
- 列表排序不正确
- 列表排序和结构体向量排序之间的性能差距.c++
- 对抽象数据类型的stl::列表排序
- C++std列表排序使用自定义比较器,该比较器依赖于对象实例的成员变量