我有问题要问。
我创建了一个名为AstarPlanlama的类,并具有以下两个函数:
bool AstarPlanlama::nodeComp(const Node* lhs, const Node* rhs)
{
return lhs->F < rhs->F;
}
void AstarPlanlama::enKucukFliNodeBul(std::list<Node*> * OPEN)
{
std::list<Node*>::iterator it = std::min_element(OPEN->begin(), OPEN->end(), &AstarPlanlama::nodeComp);
OPEN->sort(&AstarPlanlama::nodeComp);
Q = OPEN->front();
OPEN->pop_front();
}
当我编译代码时,错误发生在 xutility.h 文件中。
template<class _Pr, class _Ty1, class _Ty2> inline
bool _Debug_lt_pred(_Pr _Pred,
_Ty1& _Left, _Ty2& _Right,
_Dbfile_t _File, _Dbline_t _Line)
{ // test if _Pred(_Left, _Right) and _Pred is strict weak ordering
if (!_Pred(_Left, _Right))
return (false);
else if (_Pred(_Right, _Left))
_DEBUG_ERROR2("invalid operator<", _File, _Line);
return (true);
}
功能的缺陷:
bool nodeComp(const Node* lhs, const Node* rhs);
void enKucukFliNodeBul(std::list<Node*> * OPEN);
错误行 if(!_Pred(_Left,_Right))
代码有什么问题?
感谢您的回复..
我的问候..
答案 0 :(得分:3)
看起来您正在将成员函数作为自定义比较器传递。
设为static
或使用std::bind
:
std::list<Node*>::iterator it = std::min_element(OPEN->begin(), OPEN->end(),
std::bind(&AstarPlanlama::nodeComp,
this,
std::placeholders::_1,
std::placeholders::_2));
OPEN->sort(std::bind(&AstarPlanlama::nodeComp,
this,
std::placeholders::_1,
std::placeholders::_2));
成员函数是特殊的,需要在对象上调用,这就是绑定到std::bind
指针需要this
的原因。
答案 1 :(得分:2)
您对nodeComp()
的声明是错误的 - 如果您想遵循标准库约定,它需要是自由函数或静态函数,而不是常规成员函数。通常情况下,我建议将其设为一个标记为朋友的免费功能,以便它可以访问私人班级成员。您声明的函数不会使xutility.h中的比较器函数成为预期的函数,因为它带有“hidden this”参数,该参数由所有非静态成员函数承载。
另外,考虑到nodeComp()
的实现,没有理由将它作为常规成员函数,因为它不对其对象的数据进行操作,而是对正在传入的对象的数据进行操作作为参数。
为了简化你的生活和其他任何人必须维护代码的生命,我将遵循标准库约定并用下面的代码替换nodeComp()并在类声明中声明操作符是朋友AstarPlanlama。
bool operator<(const AstarPlanlama::Node* lhs, const AstarPlanlama::Node* rhs)
{
return lhs->F < rhs->F;
}
此外,将原始指针放入标准库容器通常是一个坏主意,因为这会导致各种有趣的生命周期管理问题。如果你绝对必须使用指针,我建议使用专为它设计的容器,如boost指针容器,或者将对象包装在std::shared_ptr
中,而不是处理原始指针。