我正在使用priority_queue来解决问题。 我打算以下面的方式声明我的节点。为什么我不能把比较器放在节点内?
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>, node> queue;
但它不工作。
然后,我切换到另一种方式。有用。
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;
我不知道为什么有差异。任何建议都会很棒。
考虑下面的答案,我已经尝试了不同的方式来运行我的代码,它们的工作原理:
版本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;
版本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;
,它不是'操作符()'被定义。你可以使用'std :: less'来使其工作,或者只是省略了编译器。 –
StoryTeller
您是否注意到'node'结构中的比较运算符和'com'结构中的函数调用运算符之间有什么区别?像一个是***比较运算符***,另一个是***函数调用***运算符? –
不是你需要第一个例子中的额外的模板参数,因为那么将会使用使用'<'运算符的默认'std :: less'。所以在第一个例子中,你需要的是'priority_queue队列;' –