优先队列
优先队列(priorityqueue)普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出(largest-in,first-out)的行为特征。
对于优先对列,在这里谈谈对结构体和一般情况的自定义优先级;
1.结构体
第一步 声明一个结构体
struct node{
int x,y;
int step;
friend bool operator <(node a,node b)
{
a.step>b.step; //定义从小到达排列
}
};
第二步 声明队列
priority_queue<node> s;
例子如下:
# include<stdio.h>
# include<queue>
# include<algorithm>
using namespace std;
struct node{
int step;
friend bool operator <(node a,node b)
{
return a.step>b.step;
}
}a;
int main(){
priority_queue<node> s;
for(int i=10,j=1;i>=1;i--,j++)
{ a.step=i;
s.push(a);
}
while(!s.empty())
{
printf("%d ",s.top().step);
s.pop();
}
return 0;
}
2.普通的
第一步 声明比较函数
struct cmp{
bool operator() (int& a,int& b)
{
return a>b;
}
};
第二步 声明队列
priority_queue<int ,vector<int >,cmp> s;
例子如下:
# include<stdio.h>
# include<queue>
# include<algorithm>
using namespace std;
struct cmp{
bool operator() (int& a,int& b)
{
return a>b;
}
};
int main(){
priority_queue<int ,vector<int >,cmp> s;
for(int i=10,j=1;i>=1;i--,j++)
{
s.push(i);
}
while(!s.empty())
{
printf("%d ",s.top());
s.pop();
}
return 0;
}