C++學習 --- STL常用容器之stack容器
阿新 • • 發佈:2021-10-11
概念: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; }