在priority_queue的自定义类中重载比较运算符

Overloading comparison operators in custom class for priority_queue

本文关键字:重载 比较 运算符 自定义 priority queue      更新时间:2023-10-16

我正在尝试使用priority_queue创建一个"number"的最小堆。"数字"是我定义的一个类,它有三个私有变量:

int value;           //This holds the value to be read in the heap
vector<int> list;    //This holds the vector where the value is gotten from
size_t index;        //This holds the index of the vector that is referenced

我在这里唯一关心的私人变量是"价值">

我使<和>运算符作为priority_queue的先决条件(我认为两者都做太过分了,但我在这里学习(:

bool operator <(const number &x) {
return (value < x.value);
}
bool operator >(const number &x) {
return (value > x.value);
}

我的优先级队列声明在这里:

priority_queue<number, vector<number>, greater<number>> heap;

每当我试图编译我的程序时,我都会收到以下错误:

c:mingwlibgccmingw326.3.0includec++bitsstl_function.h:376:20: error: no match for 
'operator>'
(operand types are 'const number' and 'const number')
{ return __x > __y; }
~~~~^~~~~
In file included from main.cpp:18:0:
number.h:59:7: note: candidate: bool number::operator>(const number&) <near match>
bool operator >(const number &x) {
^~~~~~~~

我不明白为什么编译器不能使用"number"类中重载的>运算符。有人知道为什么会发生这种错误吗?此外,我不确定是否需要发布更多的代码来解决这个问题,因为我是使用priority_queue的新手。如果我知道,请告诉我。

我在评论中被告知,我需要在运算符后面添加一个const。

bool operator <(const number &x) const {
return (value < x.value);
}
bool operator >(const number &x) const {
return (value > x.value);
}