C++ 如何创建节点结构类型的最小stl优先级队列
这是我的结构节点。 现在我使用stl优先级队列,以便从优先级队列中提取最小值,即最小值,如下所示C++ 如何创建节点结构类型的最小stl优先级队列,c++,c,vector,stl,priority-queue,C++,C,Vector,Stl,Priority Queue,这是我的结构节点。 现在我使用stl优先级队列,以便从优先级队列中提取最小值,即最小值,如下所示 struct node { node *right; node *left; int data; }; std::priority_queue<node*, std::vector<node*>, std::greater<node*> > mypq; struct compare { bool operator()(const n
struct node
{
node *right;
node *left;
int data;
};
std::priority_queue<node*, std::vector<node*>, std::greater<node*> > mypq;
struct compare
{
bool operator()(const node*& l, const node*& r)
{
return l > r;
}
};
我以前也是这样
struct node
{
node *right;
node *left;
int data;
};
std::priority_queue<node*, std::vector<node*>, std::greater<node*> > mypq;
struct compare
{
bool operator()(const node*& l, const node*& r)
{
return l > r;
}
};
std::优先级队列mypq;
但是它显示了错误,我很沮丧,请任何人帮我比较函数应该采用两个参数,这两个参数是优先级队列中元素的类型。元素的类型是
node*
,因此应该将函数定义为bool操作符()(node*l,node*r)
。现在,您可以在编写比较函数时考虑到这一点:
std::priority_queue<node*, std::vector<node*>,compare > mypq;
struct compare
{
bool operator()(const node*& l, const node*& r)
{
return l->data > r->data;
}
};
假设要使用结构的
data
字段进行比较,则此类型的functor应工作:
struct compare
{
bool operator()(node* l, node* r)
{
return l->data > r->data;
}
};
其中bool操作符()
是const
,因为调用它不应该改变它的状态。C++标准不要求它是const方法,但有些实现可能需要它,导致编译错误。