C++优先队列类似队列,但是在这个数据结构中的元素按照一定的断言排列有序。
头文件:#include<queue>
参数:priority_queue<Type, Container, Functional>,其中Type 为数据类型,Container为保存数据的容器,默认vector,Functional 为元素比较方式,默认升序
priority_queue<Type>后边两个参数不加,默认为大顶堆
代码 |
含义 |
---|---|
p.push() |
压入一个元素 |
p.pop() |
压出一个元素 |
p.top() |
返回优先队列中优先级最高的元素 |
p.empty() |
优先队列为空,返回真 |
p.size() |
返回优先队列中元素个数 |
基础使用方法:
/* priority_queue的使用 */
#include<iostream>
#include<queue>
#include<vector>
#include<functional>
using namespace std;
struct nod {
int x;
int y;
nod(int a = 0, int b = 0) :x(a), y(b) {}
};
int main() {
int a[10] = { 5,1,3,8,2,4,6,9,0,7 };
/* 大顶堆 vector<int> */
cout << "\n\n大顶堆 vector<int>:\n";
priority_queue<int>p; //priority_queue<int,vector<int> > p;
for (int i = 0; i < 10; i++)p.push(a[i]);
while (!p.empty()) {
cout << p.top()<<" ";
p.pop();
}
//9 8 7 6 5 4 3 2 1 0
/* 大顶堆 pair<int,int> */
cout << "\n\n大顶堆 pair<int,int>:\n"; //先比较first,相同的话,比较second
priority_queue<pair<int, int>>p1;
pair<int, int>a1(1, 2);
pair<int, int>a2(1, 1);
pair<int, int>a3(2, 1);
p1.push(a1);
p1.push(a2);
p1.push(a3);
while (!p1.empty()) {
cout << p1.top().first << " "<<p1.top().second<<"\n";
p1.pop();
}
// 2 1
// 1 2
// 1 1
/* 小顶堆 vector<int> */
cout << "\n\n小顶堆 vector<int>:\n";
priority_queue<int,vector<int>,greater<int> >p2; //greater<>头文件 #include<functional>
for (int i = 0; i < 10; i++)p2.push(a[i]);
while (!p2.empty()) {
cout << p2.top()<<" ";
p2.pop();
}
//0 1 2 3 4 5 6 7 8 9
/* 小顶堆 pair<int,int> */
cout << "\n\n小顶堆 pair<int,int>:\n"; //先比较first,相同的话,比较second
priority_queue<pair<int, int>,vector<pair<int,int> >,greater<pair<int,int> > >p3; //定义比较麻烦,别打错了
pair<int, int>a4(1, 2);
pair<int, int>a5(1, 1);
pair<int, int>a6(2, 1);
p3.push(a4