1. 程式人生 > 其它 >C++學習 --- STL常用容器之stack容器

C++學習 --- STL常用容器之stack容器

4、stack 容器

4.1、stack基本概念

概念:stack是一種先進後出(First In Last out,FILO)的資料結構,它只有一個出口。

棧中只有頂端的元素才可以被外界使用,因此棧不允許有遍歷行為。

棧中進入資料稱為 --- 入棧 push

棧中彈出資料稱為 --- 出棧 pop

4.2、stack常用介面

#include <iostream>
#include <stack>
using namespace std;
​
//stack棧容器
void test01() {
    //棧的特點:符合先進後出資料結構
    stack<int
> s; //入棧 s.push(10); s.push(20); s.push(30); s.push(40); ​ cout << "棧的大小:" << s.size() << endl; //只要棧不為空,檢視棧頂,並執行出棧操作 while (!s.empty()) { //檢視棧頂的元素 cout << "棧頂元素為:" << s.top() << endl; ​ //出棧 s.pop(); } cout
<< "棧的大小:" << s.size() << endl; } ​ int main() { test01(); ​ system("pause"); return 0; }