- stack是STL中的一種後進先出容器
- 可以自己實現一個棧:數據結構(4)棧和隊列->棧
- STL中的stack支持任意基本數量類型和STL容器
- stack定義於
stack.h
,命名空間std
一、構造函數
作用 |
代碼 |
說明 |
定義一個stack |
stack<typename> st; |
typename可以是任意基礎數據類型或STL容器 |
二、訪問stack內元素
- 由於隊列本身是一個先進先出的限制性結構,因此STL中只能訪問棧頂元素
stack.top()
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> st;
for(int i=1;i<=5;i++)
st.push(i);
cout<<st.top()<<endl;
return 0;
}
三、常用操作
操作 |
代碼 |
時間複雜度 |
說明 |
元素x入隊 |
st.push(x) |
O(1) |
- |
彈出棧頂元素 |
st.pop() |
O(1) |
- |
棧判空 |
st.empty() |
O(1) |
返回一個bool類型 |
訪問棧頂元素(不影響棧) |
st.top() |
O(1) |
如果隊列爲空,top()方法會報錯 |
獲得queue內元素個數 |
q.size() |
O(1) |
- |
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> st;
for(int i=1;i<=5;i++)
st.push(i);
cout<<st.top()<<endl;
st.pop();
cout<<st.top()<<endl;
cout<<st.size()<<endl;
cout<<"棧空嗎:"<<st.empty()<<endl;
for(int i=1;i<=4;i++)
st.pop();
cout<<"棧空嗎:"<<st.empty();
return 0;
}