【C++】STL标准库之stack和queue

stack的简介

与之前的string,vetcor,list不同的是,它们都被称为容器,而stack被称为容器适配器,容器适配器实际上是对特定类封装作为其底层的容器,stack底层的容器可以是任何标准的容器类模板或者其他的一些容器类。只要能支判空,获取尾部元素,尾插尾删,就可以称为stack。

而我们之前看到的string,vector,list均符合要求,但是默认情况下,我们使用的是双端队列作为其底层的默认容器。双端队列请移步STL标准库之deque

stack的使用

栈的函数相对来说较少

函数名称功能
stack()构造空的栈
empty()检测stack是否为空
size()返回stack中元素的个数
top()返回栈顶元素
push()压栈
pop()出栈

使用方式:

stack<int> s();
s.empty();
s.top();
s.push();
s.pop();

queue的简介

队列和栈相同,都是容器适配器。只要符合先进先出的操作,就可以称为队列,其底层容器可以是标准容器类模板之一,符合:检测是否为空,返回有效元素个数,返回对头元素队尾元素,入队出队就可以。

实际上标准容器中deque和list都能够满足这些要求,但是在默认情况下,我们使用的是deque作为底层容器。双端队列请移步STL标准库之deque

queue的使用

函数名称功能
queue()构造空队列
empty()判断是否为空
size()返回有效元素个数
front()返回队头元素
back()返回队尾元素
push()入队
pop()出队

优先队列priority_queue

优先队列也是一种适配器,它的第一个元素总是大于它包含的其他元素。
这个结构和堆非常相似,只要能够满足检测是否为空,返回有效元素个数,尾插尾删,即可。

优先队列priority_queue的使用

函数名称功能
priority_queue()/priority_queue(first, last)构造空的优先级队列
empty()检测优先级队列是否为空
top()返回优先级队列中最大元素(堆顶元素)
push(x)在优先级队列中插入元素x
pop()删除优先级队列中最大元素(堆顶元素)

使用方式:

#include <vector>
#include <queue>
#include <functional> // greater算法的头文件
void TestPriorityQueue()
{
	// 默认情况下,创建的是大堆,其底层按照小于号比较
	vector<int> v{3,2,7,6,0,4,1,9,8,5};
	priority_queue<int> q1;
	for (auto& e : v)
		q1.push(e);
	cout << q1.top() << endl;
	// 如果要创建小堆,将第三个模板参数换成greater比较方式
	priority_queue<int, vector<int>, greater<int>> q2(v.begin(), v.end());
	cout << q2.top() << endl;
}

注意:若在优先级队列中存放的是自定义类型的数据,那么需要在自定义类型中提供大于号和小于号的重载

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	: _year(year)
	, _month(month)
	, _day(day)
 	{}
 	bool operator<(const Date& d)const
 	{
 		return (_year < d._year) ||
 			   (_year == d._year && _month < d._month) ||
			   (_year == d._year && _month == d._month && _day < d._day);
 	}
 	bool operator>(const Date& d)const
 	{
 		return (_year > d._year) ||
 			   (_year == d._year && _month > d._month) ||
 			   (_year == d._year && _month == d._month && _day > d._day);
 	}
 	friend ostream& operator<<(ostream& _cout, const Date& d)
 	{
 		_cout << d._year << "-" << d._month << "-" << d._day;
 		return _cout;
 	}
private:
 	int _year;
 	int _month;
 	int _day;
};
void TestPriorityQueue()
{
 	// 大堆,需要用户在自定义类型中提供<的重载
 	priority_queue<Date> q1;
 	q1.push(Date(2018, 10, 29));
 	q1.push(Date(2018, 10, 28));
 	q1.push(Date(2018, 10, 30));
 	cout << q1.top() << endl;
 	// 如果要创建小堆,需要用户提供>的重载
 	priority_queue<Date, vector<Date>, greater<Date>> q2;
 	q2.push(Date(2018, 10, 29));
 	q2.push(Date(2018, 10, 28));
 	q2.push(Date(2018, 10, 30));
 	cout << q2.top() << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值