您的位置:首页 > 产品设计 > UI/UE

ACM学习历程19——queue队列容器与priority_queue优先队列容器

2016-08-27 19:47 459 查看
Queue是一种实现了一个先进先出的线性表,它的插入操作只能在队尾进行,删除操作只能在队首进行,使用queue前需要需要加入<queue>头文件。
queue容器的使用:
(一)创建queue对象:queue<类型>
对象;queue<int>  q;
(二)常用的queue操作:
(1)back():读取队尾元素;
(2)empty():如果队列空则返回真;
(3)front():读取队首元素;
(4)pop():出队;
(5)push():入队;
(6)size():返回队列中元素的个数 。
#include<iostream>
#include<string>
#include<queue>
using namespace std;

int main()
{
queue<int> q;
int i;
q.push(1);
q.push(2);
q.push(3);
q.push(4);

//back() 读取队尾元素
cout<<q.back()<<endl;

//front() 读取队首元素
cout<<q.front()<<endl;

//pop()出队
q.pop();

//遍历并出队
while(!q.empty())
{
cout<<q.front()<<" ";
q.pop();
}
cout<<endl;

//q中元素全部出队
cout<<"size="<<q.size()<<endl;
return 0;
}
对应输出:
4
1
2 3 4
size=0
priority_queue优先队列容器,插入操作只能在队尾,删除只能在队首实现,不同的是priority_queue中,队列中最大元素总是位于队首,所以出队时,并非按先进先出的原则进行,而是当前队列中的最大元素出队。
priority_queue的使用:
(一)创建priority_queue对象:
priority_queue<类型>
对象
priority_queue<int>  pq;
常用的queue操作
(二)priority_queue常用操作:
(1)empty()
如果队列空则返回真:
(2)top():读取队首元素;
(3)pop():出队;
(4)push():入队;
(5)size():返回队列中元素的个数。
#include<iostream>
#include<string>
#include<queue>
using namespace std;

int main()
{
priority_queue<int> q;
int i;
//优先级队列中最大值位于队首
q.push(1);
q.push(7);
q.push(0);
q.push(4);

//top():读取队首元素
cout<<q.top()<<endl;

//pop()出队
q.pop();

//遍历并出队
while(!q.empty())
{
cout<<q.top()<<" ";
q.pop();
}
cout<<endl;

//q中元素全部出队
cout<<"size="<<q.size()<<endl;
return 0;
}
对应输出:
7
4 1 0
size=0
(三)自定义比较函数
(1)重载“<”运算符;
#include<iostream>
#include<vector>
#include<queue>
#include<string>
using namespace std;

struct non
{
string name;
float score;
bool operator<(const non &a) const
{
if(a.score!=score)
{
return a.score>score;
}
else
{
return a.name>name;
}
}
};

int main()
{
priority_queue<non> q;
non s;
s.name="Jack";
s.score=90;
q.push(s);

s.name="chen";
s.score=90;
q.push(s);

s.name="Nacy";
s.score=60.5;
q.push(s);

s.name="Tomi";
s.score=20;
q.push(s);

while(!q.empty())
{
cout<<q.top().name<<" "<<q.top().score<<endl;
q.pop();
}

return 0;
}
对应输出:
chen 90
Jack 90
Nacy 60.5
Tomi 20
(2)重载“()”运算符。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;

struct myComp
{
bool operator()(const int &a,const int &b)
{
return a>b;
}
};

int main()
{
priority_queue<int,vector<int>,myComp> q;
q.push(4);
q.push(0);
q.push(-1);
q.push(5);
q.push(7);

while(!q.empty())
{
cout<<q.top()<<" ";
q.pop();
}
cout<<endl;

return 0;
}
输出结果:
-1 0 4 5 7
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息