【C++/STL】7. stack棧

  • 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; 	//打印5
	
	return 0;
}

三、常用操作

  • 設有stack容器st
操作 代碼 時間複雜度 說明
元素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++)	//push()方法 
		st.push(i);
		
	cout<<st.top()<<endl; 	//top()方法
	
	st.pop();				//pop()方法 
	cout<<st.top()<<endl; 	//top()方法
	
	cout<<st.size()<<endl;	//empty()方法
	cout<<"棧空嗎:"<<st.empty()<<endl;
	
	for(int i=1;i<=4;i++)	
		st.pop();
		
	cout<<"棧空嗎:"<<st.empty();	 
	
	return 0;
}

/*
5
4
4
棧空嗎:0
棧空嗎:1
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章