优先队列是队列的一种,和普通队列一样只有入队,出队,取队头等操作。并不提供查找操作。但是区别于普通队列的先入先出,优先队列按照数据的优先等级出队。对于每次的入队和出队优先队列都会按照数据的优先级做动态的调整。
1.优先队列默认的是数据大的作为高的优先级。因此在将一系列数据入队以后,最终最大的数据将在队头即q.top()的位置。
priority_queue<int> q;
标准的模板库中默认使用’<’作为优先级的比较关系。
例如:将1 2 3 4 5入到优先队列中按照<的关系来确定这些整数的优先级,即数大的优先级高。所以在出队的时候将会输出5 4 3 2 1.
2.数据越小优先级越大。
priority_queue<int, vector<int>, greater<int> >q;
第二个参数作为容器来存放数据,第三个参数作为比较函数(参数可以是一个回调的函数或者是标准库默认的)。比较结果是数小的优先级大
3.对于优先队列还可以自定义优先级。方式就是重载默认的比较关系<
注:重载的时候不能重载 >号,可能会被报错。因为在默认的优先队列中使用的是 < 来确定数据的优先级。
struct cmp
{
operator bool()(int x,int y)
return x > y;//x小的优先级高,也可以写成p[x] > p[y]的形式。
};
priority_queue<int,vector<int>,cmp>q;
#include <iostream>
#include <queue>
using namespace std;
struct cmp
{
bool operator()(int x,int y)
{
return x > y;
}
};
int main ()
{
int n;
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
priority_queue<int,vector<int>,cmp>q(a,a+n);
while (!q.empty())
{
cout << q.top() << " ";
q.pop();
}
cout << endl;
system("pause");
return 0;
}
其中vector<int>仍然是容器,cmp作为比较优先级的函数,比较结果是数据小的优先级高
4.结构体申明的方式:
typedef struct
{
int x,y;
}node;
struct cmp
{
bool operator()(const node&a,const node&b)
return a.x > b.x;
};
#include <iostream>
#include <queue>
using namespace std;
typedef struct
{
int x,y;
}node;
struct cmp
{
bool operator()(const node &a,const node &b)
{
return a.x > b.x;
}
};
int main ()
{
int n;
cin >> n;
node *arry = new node[n];
for (int i = 0; i < n; i++)
{
cin >> arry[i].x >> arry[i].y;
}
priority_queue<node,vector<node>,cmp>q(arry,arry+n);
//for (int i = 0; i < n; i++)
//{
//q.push(arry[i]);
//}
while (!q.empty())
{
cout << q.top().y << " ";
q.pop();
}
cout << endl;
system("pause");
return 0;
}
或者是:
struct node
{
int x,y;
friend bool operator < (node a,node b)
return a.x > b.x;
}
priority_queue<node>q;
在该结构中x作为数据的优先级,y作为数据。其中比较结果仍然是小的数据具有高的优先级。
#include <iostream>
#include <queue>
using namespace std;
const int maxn = 10;
struct node
{
int x,y;
friend bool operator < (node a,node b)
{
return a.x > b.x;
}
}l[maxn];
int main ()
{
int n;
while (cin >> n)
{
priority_queue<node>q;
for (int i = 0; i < n; i++)
{
cin >> l[i].x >> l[i].y;
}
for (int i = 0; i < n; i++)
{
q.push(l[i]);
}
while (!q.empty())
{
cout << q.top().y << " ";
q.pop();
}
cout << endl;
}
return 0;
}