1定义优先队列
#include<stdio.h>
#include<queue>
using namespace std;
int main()
{
priority_queue<int>q;
}
2优先队列的使用
#include<stdio.h>
#include<queue>
using namespace std;
int main()
{
priority_queue<int>q;
q.push(1);
q.push(10);
q.push(5); //进队列
int t;
while(!q.empty())//判断是否为队列为空
{
t=q.top(); //取出队首的值
printf("%d ",t);
q.pop(); //出队列
}
printf("\n");
return 0;
}
q.push( ) 进队列
q.pop()出队列
q.top( ) 取队首值
q.empty( ) 判断队列是否为空,为空返回真,否则返回假;
3队列优先级的定义
优先队列默认是从小到大,要改变的话需要重新定义优先级;
1 结构体中可以用重载符 "<" 来定义优先级
- #include<stdio.h>
- #include<queue>
- using namespace std;
- struct note
- {
- int x,y;
- bool operator < (const note &a) const //重载 "<"操作符,指定优先规则
- {
- return a.x<x;//按X从小到大排序
- return a.x>x;//从大到小
- }
- };
- int main()
- {
- priority_queue<note>q;
- return 0;
- }
2
非结构体,结构体也能用重载操作符 "( )"
#include<stdio.h>
#include<vector>
#include<iostream>
#include<queue>
using namespace std;
struct cmp
{bool operator () (const int &a,const int &b) //重载 "<"操作符,指定优先规则
{
return a>b;//从小到大排序
return a<b;//从大到小
}
};
int main()
{
priority_queue<int,vector<int>,cmp>q; //重载定义优先队列
return 0;
}
2 另一种方法
priority_queue <int,vector<int>,less<int> > q;从大到小
priority_queue <int,vector<int>,greater<int> > q;从小到大
具体用见代码:
- #include<stdio.h>
- #include<vector>
- #include<iostream>
- #include<queue>
- using namespace std;
- int main()
- { priority_queue <int,vector<int>,less<int> > q;
- q.push(1);
- q.push(10);
- q.push(5);
- int t;
- while(!q.empty())
- {
- t=q.top();
- printf("%d ",t);
- q.pop();
- }
- printf("\n");
- return 0;
- }
输出为 10 5 1;