STL 之棧

目錄ios


重要的數據結構。數據結構

操做:spa

  1. size()                                          返回實際個數
  2. empty()                                       判斷是否爲空
  3. push(item)                                 壓棧
  4. top()                                             返回棧頂元素
  5. pop()                                            將棧頂元素刪除
  6. s1.swap(s2)                               將兩個棧元素交互
  7. s1 == s1                                      判斷是否相等
注:棧沒有clear方法,若程序須要,能夠單獨編寫!
示例代碼:
#include <stack>
#include <iostream>

using namespace std;

int main() {
	stack<int> intStack;
	// 壓 4個元素入棧
	intStack.push(16);
	intStack.push(8);
	intStack.push(20);
	intStack.push(3);

	// 取棧頂元素,並彈棧
	cout << "top of intStack:" << intStack.top() << endl;
	intStack.pop();
	cout << "top of intStack:" << intStack.top() << endl;
	while(!intStack.empty()) {
		cout << intStack.top() << " ";
		intStack.pop();
	}

	cout << endl;
	return 0;
}

運行結果:
top of intStack:3 top of intStack:20 20 8 16
相關文章
相關標籤/搜索