头文件#include
定义:priority_queue
ype 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,默认用的是vector),Functional 就是比较的方式,可以自定义,默认是大顶堆
基本操作:
empty() 如果队列为空,则返回真
pop() 删除对顶元素,删除第一个元素
push() 加入一个元素
size() 返回优先队列中拥有的元素个数
top() 返回优先队列对顶元素,返回优先队列中有最高优先级的元素
#include
#include
#include
#include
using namespace std;
struct cmp1//定义比较结构
{
bool operator ()(int &x,int &y)
{
return x > y;//小顶堆
}
};
struct cmp2
{
bool operator ()(int &x,int &y)
{
return x < y;//大顶堆
}
};
struct struct1
{
int x;
bool operator < (const struct1 &y) const
{
return x > y.x;//小顶堆
}
};
struct struct2
{
int x;
bool operator < (const struct2 &y) const
{
return x < y.x;//大顶堆
}
};
int main()
{
int a[10] = {2,4,7,9,0,34,546,789,890,234};
struct1 num1[10];
struct2 num2[10];
for (int i=0;i<10;i++)
{
num1[i].x = a[i];
num2[i].x = a[i];
}
priority_queue<int>q0;//默认大顶堆
priority_queue<int,vector<int>,cmp1>q1;//小顶堆
priority_queue<int,vector<int>,cmp2>q2;//大顶堆
priority_queue<int,vector<int>,greater<int> >q3;//小顶堆
priority_queue<int,vector<int>,less<int> >q4;//大顶堆
priority_queue<struct1>q5; //小顶堆
priority_queue<struct2>q6; //大顶堆
for(int i=0; i<10; i++)
{
q0.push(a[i]);
q1.push(a[i]);
q2.push(a[i]);
q3.push(a[i]);
q4.push(a[i]);
q5.push(num1[i]);
q6.push(num2[i]);
}
cout<<"q0:"<<endl;
while(!q0.empty())
{
cout<<q0.top()<<" ";
q0.pop();
}
cout<<endl<<"q1:"<<endl;
while(!q1.empty())
{
cout<<q1.top()<<" ";
q1.pop();
}
cout<<endl<<"q2:"<<endl;
while(!q2.empty())
{
cout<<q2.top()<<" ";
q2.pop();
}
cout<<endl<<"q3:"<<endl;
while(!q3.empty())
{
cout<<q3.top()<<" ";
q3.pop();
}
cout<<endl<<"q4:"<<endl;
while(!q4.empty())
{
cout<<q4.top()<<" ";
q4.pop();
}
cout<<endl<<"q5:"<<endl;
while(!q5.empty())
{
cout<<q5.top().x<<" ";
q5.pop();
}
cout<<endl<<"q6:"<<endl;
while(!q6.empty())
{
cout<<q6.top().x<<" ";
q6.pop();
}
return 0;
}
输出
q0:
890 789 546 234 34 9 7 4 2 0
q1:
0 2 4 7 9 34 234 546 789 890
q2:
890 789 546 234 34 9 7 4 2 0
q3:
0 2 4 7 9 34 234 546 789 890
q4:
890 789 546 234 34 9 7 4 2 0
q5:
0 2 4 7 9 34 234 546 789 890
q6:
890 789 546 234 34 9 7 4 2 0