记录一个菜逼的成长。。
记下对优先队列对优先级改如何定义
这是stl里定义的比较结构
我们都知道用greater是小顶堆,less是大顶堆,默认是less。
/// One of the @link comparison_functors comparison functors@endlink.
template<typename _Tp>
struct greater : public binary_function<_Tp, _Tp, bool>
{
bool operator()(const _Tp& __x, const _Tp& __y) const
{ return __x > __y; }
};
/// One of the @link comparison_functors comparison functors@endlink.
template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
bool operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; }
};
如果我们自己定义一个结构可这样写
假设定义了一个结构
struct Node{
int x,y,z;
}
我们模仿上面的比较结构自己定义一个比较结构,比如
struct cmp{
bool operator () (const Node& a,const Node& b) const{
return a.y < b.y;//大顶堆,,改为>是小顶堆
}
}
那么创建优先队列时这样写
priority_queue<Node,vector<Node>,cmp>q;
我们也可以通过重载运算符来定义优先级,比如
struct Node{
int x,y,z;
friend bool operator > (const Node& a,const Node& b){
return a.x > b.x; //greater,小顶堆
}
friend bool operator < (const Node& a,const Node& b){
return a.x < b.x;//less,大顶堆
}
}
我们可以这样创建优先队列
priority_queue<Node,vector<Node>,greater<Node> >q;
priority_queue<Node,vector<Node>,less<Node> >q;

这篇博客记录了如何在C++中定义和使用优先队列,特别是如何自定义优先级。作者探讨了STL中优先队列的默认比较结构,并提供了使用`greater`和`less`创建小顶堆和大顶堆的例子。此外,还介绍了通过定义结构体的比较函数或重载运算符来定制优先级的方法。
49

被折叠的 条评论
为什么被折叠?



