用法
#include <stack>
底層容器默認使用的是deque。
stack提供了以下操作:入棧、出棧、判斷棧空、訪問棧頂、棧大小。
stack s1;
stack s2;
- 入棧:s.push(x) 默認是不預設棧大小的
- 出棧:s.pop() 注意出棧只是刪除棧頂元素,並不返回該元素。其原型是
value_type& top()
;另外需要自行判斷堆棧是否爲空,纔可執行。 - 訪問棧頂:s.top() 常用x=s.top(),原型:value_type& top()
- 判斷棧空:s.empty() 空時,返回true
- 棧中元素個數:s.size()
例子
1、看一個例子,輸出一組整數到棧中,然後輸出。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> s1;
int x;
while(cin>>x){
s1.push(x);//入棧
}
/*注意,下面這個結果是反着的,是先入後出*/
while(!s1.empty()){
cout<< s1.top()<<" ";//訪問棧頂
s1.pop();//出棧,即刪除棧頂元素
}
return 0;
}
輸入:2 4 6 8[ctrl+z]
輸出:8 6 4 2
注意,輸出是反着的,棧先進後出嘛,別忘了喲。
2、接下來,看一個容易出錯的情況。常常用vector後,會用下標v[i]訪問元素,但是stack不行,是出錯的,stack元素不能由下標s[i]訪問,她有s.top()。
stack<int> s1;
int x;
while(cin>>x){
s1.push(x);//入棧
}
int n= s1.size();
for(int i=0; i<n; ++i){
cout << s1[i] << endl;/* Error: stack的,不能採用[]訪問*/
}
3、我們可以預設棧的大小
#include <iostream>
#include <stack>
using namespace std;
#define MAX_SIZE 5 //預設棧的最大大小
int main()
{
stack<int> s1;
int x;
while(cin>>x){
if(s1.size()<MAX_SIZE){
s1.push(x);//入棧
}
}
while(!s1.empty()){
cout<< s1.top()<< " ";
s1.pop();
}
return 0;
}
輸入:1 2 3 4 5 6 7
輸出:5 4 3 2 1
6和7入不了棧。