天天看點

資料結構棧------STL中stack的常見用法詳解1.stack的定義2.stack容器内元素的通路3.stack常用函數

1.stack的定義

添加頭檔案
#include<stack>
using namespace std;

//stack < datatype > name;
stack < int > st;
           

2.stack容器内元素的通路

棧隻能通路棧頂元素,通過pop()

3.stack常用函數

#include<cstdio>
#include<stack>

using namespace std;

int main ()
{

	stack < int > st;
	//push() 入棧操作
	for ( int i = 1; i <= 5; i++ ){
		st.push ( i );
	}
	
	//top() 擷取棧頂元素
	printf ( "壓入元素1 2 3 4 5後,棧頂元素為%d\n", st.top () );
	
	//pop() 彈出棧頂元素(删除)
	st.pop(); 
	printf ( "壓入元素1 2 3 4 5後彈出一次棧頂元素,此時棧頂元素為%d\n", st.top ());
	
	//empty() 檢測stack内是否為空
	stack < int > st1;
	if ( st1.empty() == true )
		printf ( "Empty!\n");
	else
		printf ( "Not Empty !\n");
	st1.push ( 1 );
	if  ( st1.empty() == true )
		printf ( "Empty !\n");
	else
		printf ( "Not Empty!\n");
		
	//size() 傳回stack内元素個數
	stack < int > st2;
	for ( int i = 1; i <= 5; i++ )
		 st2.push(i);
	printf ( "棧内有%d個元素\n", st2.size() ); 
	
	return 0;
}
           

繼續閱讀