如何理解优先队列结构体或类的自定义排序方式
在结构体或类中重载小于号
首先 默认为大根堆 top为最大的元素
struct Student {
string name;
int score;
bool operator<(const Student &other) const {
return score<other.score;
}
};
priority_queue<Student>pq;
注意 结构体当然要自定义排序方式 上面的就是实现默认大根堆顺序 把score最大的放在top
看小于号方向就行了 都是重载的小于号 只要return里的不等号也是小于号 那么就是默认大根堆顺序
如果要改成小根堆 就把不等号改成大于号就行
return的方向跟重载的<相反 那么就理解为跟默认排序方式相反 就变成了小根堆
在结构体外另写仿函数
理解方式跟上面一样 但重载的是()
struct cmp{
bool operator()(const Student&a,const Student&b) const{
return a.score>b.score;//不等号方向跟上面的重载一样 这里的写法就是小根堆
}
};
//结构体中没有重载小于号
priority_queue<Student,vector<Student>,cmp>pq;
set在结构体或类中重载小于号
重载方式跟sort一样
struct node{
int x,y;
bool operator<(node other) const{
return x<other.x;
}
};
set<node>st;//按照x升序排序
关于内置数据类型的排序
– 建议直接用greater<int>
set默认升序 set<int,greater<int>>st;
就变成降序
– pq默认大根堆priority_queue<int,vector<int>,greater<int>>pq;
就变成了小根堆
– 当然也可以自己搞
写一个仿函数
记得重载的是()
不是<
set
struct cmp {
bool operator()(const int& a, const int& b) const {
return a > b; // 降序排序
}
};
set<int,cmp>st;
set的排序 就跟sort的cmp一样理解
a>b表示大的在前面 就是降序
priority_queue
默认大根堆
struct cmp {
bool operator()(const int& a, const int& b) const {
return a > b;//小根堆
}
};
priority_queue<int,vector<int>,cmp)pq;
理解方式同自定义数据类型