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

Queue是一种实现了一个先进先出的线性表,它的插入操作只能在队尾进行,删除操作只能在队首进行,使用queue前需要需要加入<queue>头文件。

queue容器的使用:

(一)创建queue对象:queue<类型> 对象;queue<int>  q;

(二)常用的queue操作:

1back():读取队尾元素;

2empty():如果队列空则返回真;

3front():读取队首元素;

4pop():出队;

5push():入队;

6size():返回队列中元素的个数 。

#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常用操作:

1empty() 如果队列空则返回真:

2top():读取队首元素;

3pop():出队;

4push():入队;

5size():返回队列中元素的个数。

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值