Stack(棧)是一種后進先出的數據結構,也就是LIFO(last in first out) ,最后加入棧的元素將最先被取出來,在棧的同一端進行數據的插入與取出,這一段叫做“棧頂”。
使用STL的stack需要include一個頭文件<stack>
構造
template <class T, class Container = deque<T> > class stack;
如上,這對尖括號中有兩個參數,第一個是T,表示棧中存放的數據的類型,比如int,double,或者結構體之類。
第二個參數指明底層實現的容器類型,也就是指明這個棧的內部實現方式,比如vector,deque,list。如果不指明它,默認使用deque(雙端隊列)。當然一般情況下不需要指定這一項參數。
直接看栗子、
// 構造 stacks #include <iostream> #include <stack> // 使用棧stack #include <vector> // vector #include <deque> // deque using namespace std; int main () { stack<int> first; //構造一個用於存放int類型的空棧(默認底層容器為deque),size=0。這是最簡單也是最常用的方式 ٩(๑❛ᴗ❛๑)۶如果感覺別的方式太復雜,會用這一種就行 deque<int> mydeque (3,100); //構造一個包含3個int元素的雙端隊列 stack<int> second (mydeque); //用自己的雙端隊列構造一個棧(size=3) stack<int,vector<int> > third; //指明用vector實現一個棧(存放int),空棧size=0 vector<int> myvector (2,200); //構造一個存放2個元素的vector stack<int,vector<int> > fourth (myvector); //用自己的vector構造一個棧,size=2 //輸出四個棧的大小 cout << "size of first: " << first.size() << endl; cout << "size of second: " << second.size() << endl; cout << "size of third: " << third.size() << endl; cout << "size of fourth: " << fourth.size() << endl; return 0; }
輸出結果:
size of first: 0 size of second: 3 size of third: 0 size of fourth: 2
成員函數
先說一些常用的,直接看栗子୧(๑•̀⌄•́๑)૭
#include <iostream> #include <stack> using namespace std; int main () { stack<int> mystack; for (int i=0; i<5; ++i) mystack.push(i); //push函數將參數元素加入棧中,沒有返回值(例如這里循環將0,1,2,3,4加入棧中,注意棧頂元素是4) cout << "size: " << mystack.size() << endl; //size函數返回棧的大小(此時有5個元素,size=5) while (!mystack.empty()) //empty函數返回一個bool值,棧為空時返回true,否則返回false { cout << ' ' << mystack.top(); //top函數的返回值是棧頂元素(注意並沒有刪掉棧頂元素) mystack.pop(); //pop函數將棧頂元素刪掉,沒有返回值 } cout << endl; return 0; }
運行結果:
size: 5 4 3 2 1 0
再來看另一組栗子:
#include <iostream> #include <stack> using namespace std; struct Node { int a,b; Node (int x, int y) { a = x; b = y; } }; int main () { stack<Node> mystack; mystack.emplace(1,2); //emplace函數可以將一個元素加入棧中,與push的區別在於:emplace可以直接傳入Node的構造函數的參數,並將構造的元素加入棧中 //mystack.push(1,2); //編譯不通過,要達到上面的效果需要手動構造,例如mystack.push(Node(1,2)); Node p = mystack.top(); cout << p.a << " " << p.b << endl; stack<Node> my2; my2.swap(mystack); //swap函數可以交換兩個棧的元素 cout << mystack.size() << " " << my2.size() << endl; return 0; }
運行結果:
1 2 0 1
以上就是stack的常規操作