不多说,懂的都懂,看代码
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct fruit{
string name;
int price;
friend bool operator <(fruit f1,fruit f2)
{
return f1.price<f2.price;
}
}f1,f2,f3;
int main()
{
//本节学习priority_queue,用堆实现的优先级队列,队首元素一定是优先级最高的那个
//定义在#include<queue>中,定义方式和其他STL容器别无二致
printf("create a priority_queue q\n");
priority_queue<int> q;
//push(x)令x入队,O(logN),N为当前队列中元素个数
printf("push 3 4 1 to q\n");
q.push(3);
q.push(4);
q.push(1);
//q.top()可以访问队首元素,返回值也是队首元素,priority_queue只有这一种访问方式
printf("now the top is %d\n",q.top());
//q.pop()可以让队首元素出队,返回值是void,O(logN)
q.pop();
printf("After pop() once the top is %d\n",q.top());
q.pop();
printf("After pop() again the top is %d\n",q.top());
printf("create a priority_queue q1 and no push\n");
priority_queue<int> q1;
printf("use q1.empty() to q1: ");
if(q1.empty()==true)
printf("Empty\n");
else
printf("Not Empty\n");
printf("use q.empty() to q: ");
if(q.empty()==true)
printf("Empty\n");
else
printf("Not Empty\n");
//size()用于返回priority_queue中的元素个数
printf("The q's size is %d\n",q.size());
//priority_queue中的优先级设置
//对于基本类型(int,double,char)来说,谁大谁优先级高,对char来说就是字典序
//以下两种定义方式是等价的
priority_queue<int> q2;
priority_queue<int, vector<int>, less<int>> q3;
//第二种定义方式多了两个参数,一个vector<int>,用来承载底层heap的容器
//一个less<int>表示数字大的优先级高,数字小的是弟弟
//所以想把数字小的元素放队首,应该这么定义:
printf("create a priority_queue q4(small first) and push 3 4 1\n");
priority_queue<int, vector<int>, greater<int>> q4;
q4.push(3);
q4.push(4);
q4.push(1);
printf("so the q4.top is %d\n",q.top());
//结构体优先级的设置,我们对水果名称和价格建立一个结构体
//并且重载了<号,这样我们可以定义价格高的水果优先队列
//如果想要价格低的水果优先级高,可以改成return f1.price>f2.price;
printf("create a priority_queue<struct_type> q5(expensive first) and push 3 fruits\n");
priority_queue<fruit> q5;
f1.name="桃子";
f1.price=3;
f2.name="梨子";
f2.price=4;
f1.name="苹果";
f1.price=1;
q5.push(f1);
q5.push(f2);
q5.push(f3);
printf("The top fruit name and price is\n");
cout<<q5.top().name<<" "<<q5.top().price<<endl;
//结构体比较庞大,建议使用常引用传参数,const fruit& f1;
return 0;
}