2.5.1引入
- stack是一种“先进后出”的容器。
- 不过值得注意的是stack是一种关联容器,是通过简单地修饰线性类deque的接口而获得的另一种“容器类”,往往被归结为配接器(adapter)而不是容器(Container)。
栈不能遍历,不支持随机存取,只能通过top从栈顶获取和删除元素。
stack 常用API学习 C++的STL库常用API–stack
2.5.2 代码示例
#include<iostream>
#include<stack>
using namespace std;
void text01()
{
//初始化
stack<int> s1;
stack<int> s2(s1);
//stack操作
s1.push(10);
s1.push(100);
s1.push(1000);
s1.push(30);
s1.push(20);
cout << "栈顶元素:" << s1.top() << endl;
//打印栈容器数据
while (!s1.empty())
{
cout << s1.top() << " ";
s1.pop();
}
cout << endl;
cout << "size:" << s1.size() << endl;//剩余元素
}
int main()
{
cout << "\ntext01\n";
text01();
return 0;
}
2.5.3 代码运行结果
总结
作为后进先出的单口容器,使用有其局限性,应该熟练掌握典型例题。
谢谢阅读(〃’ ▽ '〃)如有纰漏欢迎指出,觉得还不错就点个赞吧。