第 18.6 節
stack 容器
0瀏覽次數0訪問次數--跳出率--平均停留
stack容器
stack 基本概念
概念:stack是一種先進後出(First In Last Out,FILO)的數據結構,它只有一個出口

棧中只有頂端的元素纔可以被外界使用,因此棧不允許有遍歷行爲
棧中進入數據稱爲 --- 入棧 push
棧中彈出數據稱爲 --- 出棧 pop
生活中的棧:


stack 常用接口
功能描述:棧容器常用的對外接口
構造函數:
stack<T> stk;//stack採用模板類實現, stack對象的默認構造形式stack(const stack &stk);//拷貝構造函數
賦值操作:
stack& operator=(const stack &stk);//重載等號操作符
數據存取:
push(elem);//向棧頂添加元素pop();//從棧頂移除第一個元素top();//返回棧頂元素
大小操作:
empty();//判斷堆棧是否爲空size();//返回棧的大小
示例:
#include <iostream>
#include <stack>
using namespace std;
//栈容器常用接口
void test01()
{
//创建栈容器 栈容器必须符合先进后出
stack<int> s;
//向栈中添加元素,叫做 压栈 入栈
s.push(10);
s.push(20);
s.push(30);
while (!s.empty()) {
//输出栈顶元素
cout << "栈顶元素为: " << s.top() << endl;
//弹出栈顶元素
s.pop();
}
cout << "栈的大小为:" << s.size() << endl;
}
int main() {
test01();
return 0;
}
運行結果:
栈顶元素为: 30
栈顶元素为: 20
栈顶元素为: 10
栈的大小为:0
總結:
- 入棧 --- push
- 出棧 --- pop
- 返回棧頂 --- top
- 判斷棧是否爲空 --- empty
- 返回棧大小 --- size