0

I am trying to create a simple priority queue containing elements of class c.

The most intuitive ways seemed to be the first one, however, it gave me compile error.

Then, I tried both second and third ways, and they worked just fine.

To sum up, why the first method does not work? And, should we use one way over the others, and why?

class c {
public:
    int data;
    c(int n):data(n){};

    // First way : putting comparator inside class 
    bool operator<(c a) { 
        return data < a.data; 
    } 
};

// Second way : putting comparator outside
bool operator<(c a, c b) { 
    return a.data < b.data; 
} 

// Third way : creating a comparator class
struct Compare {
    bool operator()(c a, c b) {
        return a.data < b.data;
    }
};

int main(){
    priority_queue<c> pq;
    priority_queue<c, vector<c>, Compare> pq; // only for third method

    pq.push(c(3));
    pq.push(c(1));
    pq.push(c(2));
    pq.push(c(4));

    while (pq.size()) {
        cout << (pq.top().data);
        pq.pop();
    }
}
Sean
  • 489
  • 1
  • 8
  • 29
  • 2
    The signature of your operators are wrong. For the member function, try this: `bool operator<(const c& a) const { return data < a.data; }` and then `priority_queue pq;` will work. Do the same for the free function and `Compare` if you'd like to keep them. – Ted Lyngmo Aug 15 '19 at 07:28
  • 3
    when you have compiler errors you should include them in the question. For comparison of first and second option see the duplicate. The thrid isn't really considered as overloading, though often that is the prefered one for sorting. Consider a class `table`, there is no natural way of ordering but still you sometimes want to sort them according to size, another time according to widht or weight etc – 463035818_is_not_an_ai Aug 15 '19 at 07:47
  • @TedLyngmo -- comparators are allowed to take their arguments by value. That is, `bool operator<(c a);` and `bool operator<(const c& a);` are both acceptable. Your rewrite **also** marks the member function as const, and that is probably the actual solution. Either `bool operator<(c a) const;` or `bool operator<(const c& a);` would work. – Pete Becker Aug 15 '19 at 12:55
  • @PeteBecker True, I should have pointed out what part that made it impossible to compile and also _recommended_ making the argument `const c&`. – Ted Lyngmo Aug 15 '19 at 16:23

0 Answers0