优先队列
作者:
QG_office
,
2023-04-03 21:58:16
,
所有人可见
,
阅读 267
#include <bits/stdc++.h>
#include <queue>
using namespace std;
struct temp1
{
int x;
temp1(int a) {x = a;}
bool operator<(const temp1& a) const
{
return x < a.x;
}
};
struct temp2
{
bool operator() (temp1 a, temp1 b)
{
return a.x < b.x;
}
};
int main()
{
priority_queue<int> a;
priority_queue<int, vector<int>, greater<int> > c;
priority_queue<string> b;
for(int i = 0; i < 5; i ++)
{
a.push(i);
c.push(i);
}
while(!a.empty())
{
cout<<a.top()<<' ';
a.pop();
}
cout<<endl;
while(!c.empty())
{
cout<<c.top()<<' ';
c.pop();
}
cout<<endl;
b.push("abc");
b.push("abcd");
b.push("cbd");
while(!b.empty())
{
cout<<b.top()<<' ';
b.pop();
}
cout<<'\n'<<endl;
cout<<"pair 写优先队列"<<endl;
priority_queue<pair<int, int> >aa;
pair<int, int> bb(1, 2);
pair<int, int> cc(1, 3);
pair<int, int> dd(2, 5);
aa.push(dd);
aa.push(cc);
aa.push(bb);
while(!aa.empty())
{
cout<<aa.top().first<<' '<<aa.top().second<<'\n';
aa.pop();
}
cout<<'\n'<<endl;
cout<<"用自定义类型做优先队列元素的例子"<<endl;
temp1 aaa(1);
temp1 bbb(2);
temp1 ccc(3);
priority_queue<temp1> ddd;
ddd.push(bbb);
ddd.push(ccc);
ddd.push(aaa);
while(!ddd.empty())
{
cout<<ddd.top().x<<'\n';
ddd.pop();
}
cout<<endl;
priority_queue<temp1, vector<temp1>, temp2> f;
f.push(bbb);
f.push(ccc);
f.push(aaa);
while(!f.empty())
{
cout<<f.top().x<<'\n';
f.pop();
}
return 0;
}