stack是⼀种满⾜⼀定约束的线性数据结构。其约束是:只允许在栈的⼀端插⼊或删除元素,这⼀端被称为 栈顶;相对地,我们把另⼀端称为 栈底。
引入栈
C++中stack
的实现在<stack>
头文件和std
命名空间中,在代码开头引用这个头文件。
#include <stack>
using namespace std;
构造⼀个空栈
C++ 中直接构造⼀个 stack 的语句为:
stack<type> stk; //type可以是int char string ...
常用函数
方法 | 说明 |
---|---|
push(x) | 压入元素x到栈顶 |
pop() | 弹出栈顶元素 |
top() | 返回栈顶元素 |
empty() | 判断容器是否为空 |
size() | 返回栈元素的个数 |
附:
size() 调用方式: int n = stk.size();
实例
- 清空栈
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<string> stk;
stk.push("aaa");
stk.push("bbb");
stk.push("ccc");
while (!stk.empty()) //等价于 while(stk.size())
stk.pop();
cout << stk.size();
return 0; //output:0
}
- 模拟栈
#include <iostream>
using namespace std;
const int N = 1010;
int stk[N], tt;
int main()
{
stk[++tt] = 111;
stk[++tt] = 222;
stk[++tt] = 333;
cout << stk[tt] << " "; //取栈顶元素 stk.top()
while (tt)
tt--; //弹出栈顶元素 stk.pop()
cout << tt; //取栈的大小 stk.size()
return 0; // output:333 0
}
轻松一下
戴上耳机,享受电音带来的视觉盛宴吧!【如有错误,敬请留言】