C++的stack和queue


一、栈stack

LIFO: Last In First Out 后进先出

1.头文件

#include<stack>

2.函数

函数返回值作用
stack s;声明一个存储T类型数据的栈
stack s2(s1)拷贝构造
s.push(T n);void将T类型数据n压入栈的顶端
s.pop()void弹出顶层元素
s.top()T获得顶层元素的值
s.size()int返回栈中元素的个数
s.empty()bool返回真表示空栈,假表示非空栈
s1.swap(s2)或者swap(s1,s2)void交换两个栈

除此之外,容器vector的别的都没有,尤其是没有[]获取下标元素和push_back()(是push())。

3.例子

#include<iostream>
#include<stack>
using namespace std;
int main()
{
	stack<int> s;						//声明存储int类型数据的栈
	s.push(1);							//{}→{1} 
	s.push(2);							//{1}→{2,1}
	s.push(3);							//{2,1}→{3,2,1}
	cout << s.size() << endl;			//3
	cout << s.top() << endl;			//3
	s.pop();							//{3,2,1}→{2,1}
	cout << s.top() << endl;			//2
	s.pop();							//{2,1}→{1}
	cout << s.top() << endl;			//1
	s.pop();							//{1}→{}
	return 0;
}

二、队列queue

FIFO: First In First Out 先进先出

1.头文件

#include<queue>

2.函数

函数返回值作用
queue q;声明一个存储T类型数据的队列
queue q2(q1)拷贝构造
q.push(T n);void将T类型数据n压入队列尾端
q.pop()void弹出队首元素
q.front()T获得队首元素的值
q.back()T获得队尾元素的值
q.size()int返回队列中元素的个数
q.empty()bool返回真表示空队列,假表示非空队列
q1.swap(q2)或者swap(q1,q2)void交换两个队列

除此之外,容器vector的别的都没有,尤其是没有[]获取下标元素。

3.例子

#include<iostream>
#include<queue>
using namespace std;
int main()
{
	queue<int> q;					//声明存储int类型数据的队列 
	q.push(1);						//{}→{1} 
	q.push(2);						//{1}→{1,2}
	q.push(3);						//{1,2}→{1,2,3}
	cout << q.size() << endl;		//3
	cout << q.front() << endl;		//1
	cout << q.back() << endl;		//3
	q.pop();						//{1,2,3}→{2,3}
	cout << q.front() << endl;		//2
	q.pop();						//{2,3}→{3}
	cout << q.front() << endl;		//3
	q.pop();						//{3}→{}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值