重载运算符<用于优先级队列

Overloading operator< for priority queue

本文关键字:用于 优先级 队列 lt 运算符 重载      更新时间:2023-10-16

我正在尝试为我这样创建的类创建一个优先级队列-

std::priority_queue<Position> nodes;

我使<操作员处于这样的位置-

bool Position::operator<(Position& right) {
    return (fvalue < right.getFValue());
}

然而,每当我尝试编译时,我都会收到一条错误消息,上面写着<操作员没有过载-

error: no match for ‘operator<’ in ‘__x < __y’
position.h:30: note: candidates are: bool Position::operator<(Position&)

我在这里错过了什么?感谢您的帮助。

关系运算符不应该更改操作数。尝试:

bool Position::operator<(const Position& right) const {

我的猜测是__x__y(或两者)都是const。如果__xconst,则不能在其上调用非常数成员函数;如果__yconst,而right不是,则不能将__y作为right参数传递。

  1. 最好不要为了满足集合而重载比较运算符。(http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading)。如果可能的话,最好使用比较器对象或函数。如果你的运算符定义了这些对象的内在顺序,而不仅仅是它们在队列中的优先级,那么这是可以的。但如果不是,如果另一个开发人员在另一个上下文中使用你的运算符,你可能会遇到麻烦。

  2. 我不确定fvalue是什么,但可能没有为它定义operator <