2

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.

  • 1
    Typo? Change `bool operator >(const number &x)` -> `bool operator >(const number &x) const` and the same for `<` It's trying to call with a const object and const parameter. – Richard Critten Nov 14 '19 at 22:04
  • 1
    Don't forget about const correctness. If your member function doesn't modify anything, you should mark it `const` by default to get compiler enforcement of that. – NathanOliver Nov 14 '19 at 22:05
  • 1
    I added the const and it seems to compile now. Thanks for the input, but I don't understand why the compilation of my program hinged entirely on adding const to the functions. – Powerracer251 Nov 14 '19 at 22:07
  • 1
    @Powerracer251 `std::greater`'s signature is `operator()( const T& lhs, const T& rhs )`. Since the objects are now "const", you can only call const qualified functions on it. – NathanOliver Nov 14 '19 at 22:11
  • 1
    @NathanOliver I see. Thanks for letting me know, I am still pretty green with this kind of stuff. – Powerracer251 Nov 14 '19 at 22:13

1 Answers1

2

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);
}