c++ STL重拾——stack使用

用法

#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入不了栈。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章