C++stack(堆棧)是一個容器的改編,它實現了一個先進後出的數據結構(FILO)
使用該容器時需要包含#include<stack>頭文件;
定義stack對象的示例代碼如下:
stack<int>s1;
stack<string>s2;
stack的基本操作有:
1.入棧:如s.push(x);
2.出棧:如 s.pop().注意:出棧操作只是刪除棧頂的元素,並不返回該元素。
3.訪問棧頂:如s.top();
4.判斷棧空:如s.empty().當棧空時返回true。
5.訪問棧中的元素個數,如s.size();
下面舉一個簡單的例子:
- #include<iostream>
- #include<stack>
- using namespace std;
- int main(void)
- {
- stack<double>s;//定義一個棧
- for(int i=0;i<10;i++)
- s.push(i);
- while(!s.empty())
- {
- printf("%lf\n",s.top());
- s.pop();
- }
- cout<<"棧內的元素的個數爲:"<<s.size()<<endl;
- return 0;
- }