C++ 在优先级队列的自定义类中重载比较运算符

C++ 在优先级队列的自定义类中重载比较运算符,c++,priority-queue,min-heap,C++,Priority Queue,Min Heap,我正在尝试使用优先级队列创建一个最小的“number”堆。“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 o

我正在尝试使用优先级队列创建一个最小的“number”堆。“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
int值//它保存要在堆中读取的值
向量表//这将保存从中获取值的向量
尺寸指数//它保存被引用向量的索引
我唯一关心的私有变量是“值”

作为优先级队列的先决条件,我重载了<和>操作符(我认为两者都做太过分了,但我在这里学习):

bool运算符(常量编号&x){
返回值(值>x.value);
}
我的优先级队列的声明如下:

priority_queue<number, vector<number>, greater<number>> heap;
priority\u队列堆;
每当我试图编译我的程序时,都会出现以下错误:

c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\stl_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) {
              ^~~~~~~~
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\stl\u函数。h:376:20:错误:与
“操作员>”
(操作数类型为“常量编号”和“常量编号”)
{return\uuuux>\uuuuy;}
~~~~^~~~~
在main.cpp:18:0中包含的文件中:
编号:h:59:7:注:候选编号:布尔编号::运算符>(常数编号&)
布尔运算符>(常数编号和x){
^~~~~~~~

我不明白为什么编译器不能使用“number”中的重载>运算符类。是否有人了解发生此错误的原因?此外,我不确定是否需要发布更多代码以解决此问题,因为我不熟悉使用优先级队列。如果需要,请告诉我。

在注释中通知我需要在运算符后添加常量

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

bool operator >(const number &x) const {
    return (value > x.value);
}
bool运算符(常量编号和x)常量{
返回值(值>x.value);
}

Typo?更改
bool操作符>(常量编号和x)
->
bool操作符>(常量编号和x)const
也一样,请不要忘记const的正确性。如果您的成员函数不修改任何内容,您应该在默认情况下将其标记为
const
,以获得编译器对其的强制执行。我添加了const,现在它似乎可以编译了。感谢您的输入,但我不明白为什么我的程序的编译会失败依靠向函数中添加常量。@Powerracer251
std::greater
的签名是
operator()(const T&lhs,const T&rhs)
。由于对象现在是“const”,您只能在其上调用const限定函数。@NathanOliver我明白了。谢谢您让我知道,我对这类东西还是很熟悉的。
bool operator <(const number &x) const {
    return (value < x.value);
}

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