自定义类中的priority_queue

时间:2019-11-14 22:02:53

标签: c++ priority-queue min-heap

我正在尝试使用priority_queue创建最小数量为“ 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

我在这里唯一关心的私有变量是“值”。

我将<和>运算符重载作为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:\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) {
              ^~~~~~~~

我不明白为什么编译器不能使用“ number”类中的重载>运算符。是否有人对为什么会发生此错误有任何见解?另外,我不确定是否需要发布更多代码来解决此问题,因为我是使用priority_queue的新手。如果可以,请告诉我。

1 个答案:

答案 0 :(得分:1)

我在评论中被告知我需要在操作符之后添加一个const。

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

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