22.1 stack容器
(1) stack容器简介
- stack是堆栈容器,是一种“先进后出”的容器。
- stack是简单地装饰deque容器而成为另外的一种容器。
- 添加头文件:
#include <stack>
(2)stack对象的默认构造
- stack采用模板类实现, stack对象的默认构造形式: stack stkT;
stack <int> stkInt;//一个存放int的stack容器。
stack <float> stkFloat;//一个存放float的stack容器。
stack <string> stkString;//一个存放string的stack容器。
…
//尖括号内还可以设置指针类型或自定义类型。
(3)stack的push()与pop()方法
stack.push(elem);//往栈头添加元素stack.pop();//从栈头移除第一个元素
(4)stack对象的拷贝构造与赋值
stack(const stack &stk);//拷贝构造函数stack& operator=(const stack &stk);//重载等号操作符
(5)stack的数据存取
stack.top();//返回最后一个压入栈元素
(6)stack的大小
stack.empty();//判断堆栈是否为空stack.size();//返回堆栈的大小
完整示例代码:
#include <iostream>
#include <stack>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
stack<int> s;
srand(time(NULL));
int num;
for (int i = 0; i < 10; i++)
{
num = rand() % 10;
s.push(num);
cout << num << "进栈成功" << endl;
}
cout << "********************" << endl;
cout << "栈顶元素是 " << s.top() << endl;
cout << "栈的大小" << s.size() << endl;
//栈和队列不存在遍历,不存在迭代器
//s.begin();
cout << "********************" << endl;
while (!s.empty())
{
cout << s.top() << "出栈" << endl;
s.pop();
}
return 0;
}
运行结果:

22.2 queue容器
(1)queue容器简介
- queue是队列容器,是一种“先进先出”的容器。
- queue是简单地装饰deque容器而成为另外的一种容器。
- 需要添加头文件:
#include <queue>
(2)queue对象的默认构造
- queue采用模板类实现,queue对象的默认构造形式:queue queT; 如:
queue<int> queInt;//一个存放int的queue容器。
queue<float> queFloat;//一个存放float的queue容器。
queue<string> queString;//一个存放string的queue容器。
…
//尖括号内还可以设置指针类型或自定义类型。
(3)queue的push()与pop()方法
queue.push(elem);//往队尾添加元素queue.pop();//从队头移除第一个元素
(4)queue对象的拷贝构造与赋值
queue(const queue &que);//拷贝构造函数queue& operator=(const queue &que);//重载等号操作符
(5)queue的数据存取
queue.back();//返回最后一个元素queue.front();//返回第一个元素
(6)queue的大小
queue.empty();//判断队列是否为空queue.size();//返回队列的大小
完整示例代码:
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
for (int i = 0; i < 10; i++)
{
q.push(i);
cout << i << "进队成功" << endl;
}
cout << "********************" << endl;
cout << "队头元素" << q.front() << endl;
cout << "队尾元素" << q.back() << endl;
cout << "队列大小" << q.size() << endl;
cout << "********************" << endl;
while (!q.empty())
{
cout << q.front() << "出队" << endl;
q.pop();
}
return 0;
}
运行结果:




















![[LeetCode周赛复盘] 第 99 场双周赛20230304](https://img-blog.csdnimg.cn/29efccd622324263a465663b95d102a8.png)