2013-03-26 42 views
2
struct node 
{ 
node *right; 
node *left; 
int data; 
}; 

这是我的结构节点。 现在我正在使用顺序STL优先级队列中提取分钟即最小从优先级队列这样如何创建节点结构类型的Min stl priority_queue

std::priority_queue<node*, std::vector<node*>, std::greater<node*> > mypq; 

但我没有得到的最​​小和google搜索,我发现(较大),它用于整数,我得到了另一个答案,我实现这样的

struct compare 
{ 
bool operator()(const node*& l, const node*& r) 
    { 
    return l > r; 
    } 
}; 

而且我用这样的

std::priority_queue<node*, std::vector<node*>,compare > mypq; 

但它显示错误,我很沮丧,任何BOD请帮助我

回答

3

比较函数应该有两个参数,它们是优先级队列中元素的类型。你的元素的类型是node*,所以你的函数应该定义为bool operator()(node* l, node* r)。现在,你可以写的比较函数考虑到这一点:

struct compare 
{ 
    bool operator()(node* l, node* r) 
    { 
    return l->data > r->data; 
    } 
}; 
2
struct compare 
{ 
bool operator()(const node*& l, const node*& r) 
    { 
    return l->data > r->data; 
    } 
}; 
1

假设你想使用该结构的data领域来比较,这种类型的仿函数应该工作:

struct compare 
{ 
    bool operator()(const node* l, const node* r) const 
    { 
    return l->data > r->data; 
    } 
}; 

其中bool operator()const,因为调用它不应该改变它的状态。 C++标准并不要求它是一个const方法,但有些实现可能需要它,导致编译错误。

+1

伟大的一点,我总是错过''const''。 – gongzhitaao 2013-03-26 17:21:14

相关问题