c++STL栈与队列(stack queue)

STL(堆栈与队列)

栈(stack):

includ<stack>
stack<xx> a 定义类型为xx的栈a

a.push()压栈
a.pop()出栈
a.top()返回栈顶元素
a.size()返回栈内元素个数
a.empty()判断栈内是否为空

队列(queue):

include<queue>
queue<xx> a定义类型为xx的队列a

a.push()入队
a.pop()出队
a.front()返回队头元素
a.back()返回队尾元素
a.size()返回队列内元素个数
a.empty()判断队内是否为空

优先队列(priority_queue)

简单简绍

优先队列相较普通队列来说只是出队顺序不同

include<queue>
queue<xx> a定义类型为xx的队列a

a.push()入队
a.pop()出队
a.top()返回队头元素
a.size()返回队列内元素个数
a.empty()判断队内是否为空

  1. 如果,队列类型为简单类型
    如:int double
    可以采用**默认(先大后小)**方式输出

    priority_queue <xx,vector<xx>,less<xx> >a
    这是默认的排序方式的定义方法
    也可简化为----->priority_queue <xx>a
    如:
    priority_queue <int,vector<int>,less<int>a
    priority_queue <int>a

    也可以采用自定义方式输出

    priority_queue <xx,vector<xx>,greater<xx> >a;
    通过这种方式定义xx的简单类型优先队列会**非默认 (先小后大)**方式输出
    如:
    priority_queue <int,vector<int>,greater<int> >a;

  2. 如果有需要 ,队列类型为结构体
    如下:自定义出队方式

#include<iostream>
#include<queue>
using namespace std;
struct ew
{
	int x;
	int y;
	
};
bool operator<(ew a, ew b)//这里的小于号对应--->优先队列定义中less,less则重载<
{
	return a.y > b.y;//以结构体中y值大小决定出队顺序(从小到大)
	//return a.y<b.y;//(从大到小)
}
priority_queue<ew, vector<ew>, less<ew>> qu;
ew e_w[8];
int main()
{
	e_w[0] = { 1,3 };e_w[1] = { 2,5 };e_w[2] = { 0,4 };
	e_w[3] = { 7,6 };e_w[4] = { 3,8 };e_w[5] = { 6,2 };
	cout << "入队前:";
	for (int i = 0; i < 6; i++)
	{
		cout << '(' << e_w[i].x << ',' << e_w[i].y << ')' << " ";
		qu.push(e_w[i]);
	}
	cout << endl;
	cout << "入队后:";
	while (!qu.empty())
	{
		cout <<'('<<qu.top().x<<','<< qu.top().y <<')'<< " ";
		qu.pop();
	}
	system("pause");
	return 0;
}

看结果

入队前: (1,3) (2,5) (0,4) (7,6) (3,8) (6,2)
出队顺序:(6,2) (1,3) (0,4) (2,5) (7,6) (3,8)

另一种定义方式

#include<iostream>
#include<queue>
using namespace std;
struct ew
{
	int x;
	int y;

};
bool operator>(ew a, ew b)//这里的小于号对应--->优先队列定义中greater,greater则重载>
{
	return a.x > b.x;//以结构体中x值大小决定出队顺序(从小到大)
	//return a.x<b.x;//(从大到小)
}
priority_queue<ew, vector<ew>, greater<ew>> qu;
ew e_w[8];
int main()
{
	e_w[0] = { 1,3 }; e_w[1] = { 2,5 }; e_w[2] = { 0,4 };
	e_w[3] = { 7,6 }; e_w[4] = { 3,8 }; e_w[5] = { 6,2 };
	cout << "入队前:";
	for (int i = 0; i < 6; i++)
	{
		cout << '(' << e_w[i].x << ',' << e_w[i].y << ')' << " ";
		qu.push(e_w[i]);
	}
	cout << endl;
	cout << "入队后:";
	while (!qu.empty())
	{
		cout << '(' << qu.top().x << ',' << qu.top().y << ')' << " ";
		qu.pop();
	}
	system("pause");
	return 0;
}

看结果

入队前:(1,3) (2,5) (0,4) (7,6) (3,8) (6,2)
出队顺序:(0,4) (1,3) (2,5) (3,8) (6,2) (7,6)

综上两种结构体优先队列出队方式比较
可以看出
对于结构体类型队列来说less与greater用哪个都可以实现由大到小和由小到大两种出队方式
需要注意的是

less要重载<
greater要重载>

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值