C++STL— stack和queue的介绍及使用

stack

stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其只能从容器的一端进行元素的插入与提取操作。

stack的定义方式

方式一: 使用默认的适配器定义栈。

stack<int> st1;

方式二: 使用特定的适配器定义栈。

stack<int, vector<int>> st2;

stack<int, list<int>> st3;

注意: 如果没有为stack指定特定的底层容器,默认情况下使用deque。

stack的使用

stack当中常用的成员函数如下:

示例:

#include <iostream>
#include <vector>
#include <list>
#include <stack>
using namespace std;

int main()
{
	stack<int, vector<int>> st;
    //stack<int, list<int>> st;//用的list容器
    //stack<int> st //默认用的是deque容器
	st.push(1);
	st.push(2);
	st.push(3);
	st.push(4);
	cout << st.size() << endl; //4
	while (!st.empty())
	{
		cout << st.top() << " ";
		st.pop();
	}
	cout << endl; //4 3 2 1
	return 0;
}

 queue

队列是一种容器适配器,专门用在具有先进先出操作的上下文环境中,其只能从容器的一端插入元素,另一端提取元素。

queue的定义方式

方式一: 使用默认的适配器定义队列。

queue<int> q1;

方式二: 使用特定的适配器定义队列。

queue<int, vector<int>> q2;

queue<int, list<int>> q3;

注意: 如果没有为queue指定特定的底层容器,默认情况下使用deque。

queue的使用

queue当中常用的成员函数如下:

 示例:

#include <iostream>
#include <vector>
#include <list>
#include <queue>
using namespace std;

int main()
{
	queue<int, list<int>> q;
    //queue<int, vector<int>> st;//用的vector容器
    //queue<int> st //默认用的是deque容器
	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);
	cout << q.size() << endl; //4
	while (!q.empty())
	{
		cout << q.front() << " ";
		q.pop();
	}
	cout << endl; //1 2 3 4
	return 0;
}

C++STL— stack和queue的介绍及使用内容到此介绍结束了,感谢您的阅读!!!

如果内容对你有帮助的话,记得给我点个赞——做个手有余香的人。感谢大家的支持!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值