学习日常----stack容器示例

C++ Stack(堆栈) 是一个容器类的改编,为程序员提供了堆栈的全部功能,——也就是说实现了一个先进后出的数据结构。

c++ stl栈stack的成员函数介绍

操作 比较和分配堆栈

empty() 堆栈为空则返回真

pop() 移除栈顶元素

push() 在栈顶增加元素

size() 返回栈中元素数目

top() 返回栈顶元素

例题应用:https://vjudge.net/problem/Aizu-ALDS1_3_A

 

#include<iostream>
#include<cstdlib>
#include<stack>
using namespace std;
int main(){
    stack<int> S;
    int a,b,x;
    string s;
    while(cin>>s){
        if(s[0]=='+'){
            a=S.top();S.pop();
            b=S.top();S.pop();
            S.push(a+b);
        }
        else if(s[0]=='-'){
            b=S.top();S.pop();
            a=S.top();S.pop();
            S.push(a-b);
        }
        else if(s[0]=='*'){
            a=S.top();S.pop();
            b=S.top();S.pop();
            S.push(a*b);
        }
        else{
            S.push(atoi(s.c_str()));//将string对象转化为char*对象
        }
    }
    cout<<S.top()<<endl;
    return 0;
}

 

posted @ 2021-03-03 15:55  AA、  阅读(58)  评论(0编辑  收藏  举报