简体   繁体   中英

Overloading comparison operators in custom class for priority_queue

I am trying to create a min heap of "number" using priority_queue. "number" is a class defined by me that has three private variables:

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

The only private variable that I am concerned about here is "value."

I overloaded the < and > operators as a prerequisite for the priority_queue (I think it's overkill to do both, but I am learning here):

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

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

The declaration of my priority queue is here:

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

Whenever I try to compile my program I get this error:

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) {
              ^~~~~~~~

I don't understand why the compiler can't use my overloaded > operator from the "number" class. Does anyone have any insight as to why this error is occurring? Also, I am not sure if I need to post more code for this problem to be solvable as I am new to using priority_queue. If I do, let me know.

I was informed in the comments that I needed to add a const after my operators.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM