Search code examples
c++priority-queue

Why can't I put the comparator inside the node?


I am using priority_queue to solve a problem. I intend to declare my node in the following way.

struct node{
         int x, y, val;
         node(int _x, int _y, int _val){
             x = _x;
             y = _y;
             val = _val;
         }
         bool operator < (const node& rhs) const{
             return val > rhs.val;
         }
     };

and use it in the following way:

priority_queue<node, vector<node>, node> queue;

But it doesn't work.

Then, I switch to another way. It works.

struct node{
         int x, y, val;
         node(int _x, int _y, int _val){
             x = _x;
             y = _y;
             val = _val;
         }

     };
struct com{
    bool operator () (const node& lhs, const node& rhs) const{
             return lhs.val > rhs.val;
         }
};
priority_queue<node, vector<node>, com> queue;

I don't know why there is a difference. Any advice would be great.

Given the following answer, I have tried different ways to run my code, they works:

Version 1

struct node{
         int x, y, val;
         node(int _x, int _y, int _val){
             x = _x;
             y = _y;
             val = _val;
         }
         node(){}

        bool operator () (const node& lhs, const node& rhs) const{
         return lhs.val > rhs.val;
     }
 };

priority_queue<node, vector<node>, node> queue;

Version 2:

struct node{
         int x, y, val;
         node(int _x, int _y, int _val){
             x = _x;
             y = _y;
             val = _val;
         }
    bool operator < (const node& rhs) const{
         return val > rhs.val;
     }

 };
priority_queue<node, vector<node>, less<node>> queue;
//or
//priority_queue<node, vector<node>> queue;
//or
//priority_queue<node> queue;

Solution

  • node isn't default constructible and it doesn't have operator()

    Since you're using operator<, you don't need to specify the comparator, because the default is std::less<T>, which uses it if its available. And if you don't need to specify comparator, there's no reason to specify container, as std::vector<T> is already the default.

    priority_queue<node, vector<node>, less<node>> queue; 
    // same as
    priority_queue<node, vector<node>> queue;
    // also same as
    priority_queue<node> queue;