wangzishan - 18 days ago 4x
C++ Question

# 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;