一、stack容器概述
stack
容器適配器是C++標準模板庫(STL)中實現后進先出(LIFO)數據結構的重要組件,它通過封裝底層容器(如deque
/vector
/list
)提供棧操作接口。
二、stack核心操作詳解
1. 容器構造方式
// 默認使用deque存儲元素
stack<int> staInt; // 顯式指定底層容器
stack<int, vector<int>> vecStack;
stack<int, list<int>> listStack;
stack<int, deque<int>> dequeStack;
deque
:默認底層容器,支持快速首尾操作vector
:需要包含頭文件<vector>
list
:需要包含頭文件<list>
2. 元素操作函數
staInt.push(1); // 壓棧操作
staInt.push(2);
staInt.pop(); // 彈出棧頂元素(需保證棧非空)
staInt.push(3);
3. 棧頂訪問與修改
int& iTop = staInt.top(); // 獲取棧頂的引用
iTop = 66; // 通過引用直接修改棧頂值
staInt.top() = 88; // 直接修改棧頂元素
4. 容器狀態查詢
cout << "棧大小: " << staInt.size() << endl;
cout << "是否為空: " << boolalpha << staInt.empty() << endl;
5. 棧遍歷與清空
while (!staInt.empty()) {cout << staInt.top() << " ";staInt.pop(); // 必須彈出才能訪問下層元素
}
三、關鍵特性解析
-
底層容器選擇:
vector
:動態數組實現,push
/pop
需要O(1)攤銷時間list
:鏈表實現,所有操作保證O(1)時間復雜度deque
(默認):分塊數組實現,綜合性能最優
-
元素訪問特性:
top()
返回引用,可直接修改棧頂元素- 修改棧頂元素不會改變棧的結構特性
-
安全操作規范:
- 調用
pop()
前必須確保棧非空 - 使用
empty()
判斷替代size() == 0
更高效
- 調用
四、典型應用場景
- 函數調用棧模擬
- 括號匹配驗證
- 表達式求值(逆波蘭式)
- 撤銷操作實現
五、完整代碼回顧
#include <iostream>
#include <vector>
#include <stack>
#include <list>
#include <deque>using namespace std;int main(void) {// stack對象的默認構造// stack<int> staInt; // 默認使用deque存儲元素// stack<int, vector<int>> staInt;// stack<int, list<int>> staInt;stack<int, deque<int>> staInt;// stack的push()與pop()方法staInt.push(1);staInt.push(2);// staInt.pop();staInt.push(3);// int iTop = staInt.top();int& iTop = staInt.top();iTop = 66;cout << "staInt.top: " << staInt.top() << endl;staInt.top() = 88;cout << "staInt.size: " << staInt.size() << endl;cout << "staInt.top: " << staInt.top() << endl;while (!staInt.empty()) {cout << staInt.top() << " ";staInt.pop(); // 棧頂的元素出棧}cout << endl;system("pause");return 0;
}
六、代碼執行流程
- 使用
deque
作為底層容器構造棧 - 依次壓入1、2、3(注釋掉了pop操作)
- 演示通過引用修改棧頂元素
- 輸出修改后的棧頂值
- 遍歷并清空棧
輸出結果:
staInt.top: 66
staInt.size: 3
staInt.top: 88
88 2 1
七、注意事項
- 空棧操作防護:執行
top()
或pop()
前必須檢查empty()
- 元素生命周期:存儲對象時注意引用有效性
- 容器選擇原則:根據操作頻率選擇最優底層容器
- 異常安全:修改棧頂元素時需考慮可能引發的異常