c_cpp 使用Vector PopBack进行堆栈实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 使用Vector PopBack进行堆栈实现相关的知识,希望对你有一定的参考价值。

#include<bits/stdc++.h>
using namespace std;

// #Stack #BasicProblem

bool Top(vector<int> &a,int &top){
    if(a.size()==0){
        return false;
    }else{
        top=a[a.size()-1];
    }
}
void Push(vector<int> &a,int push){
    a.push_back(push);
}
bool Pop(vector<int> &a){
    if(a.size()==0){
        return false;
    }else{
        a.pop_back();
    }
}
int main(){
    cout<<"Instructions: \n";
    cout<<"Type add to push onto stack"<<endl;
    cout<<"Type del to pop from stack"<<endl;
    cout<<"Type top to check the top element in stack"<<endl;
    cout<<"Type exit to stop using the stack"<<endl;
    vector<int> Stack;
    int top;
    while(1){
        string instruction;
        cout<<"Instruction: ";
        cin>>instruction;
        if(instruction=="exit"){
            break;
        }else if(instruction=="add"){
            cout<<"Enter the element top be pushed"<<endl;
            int push; //element to be pushed
            cin>>push;
            Push(Stack,push);
                cout<<"Element successfully pushed"<<endl;
                if(Top(Stack,top)==true){
                    cout<<"Top Element is:"<<top<<endl;
                }

        }else if(instruction=="del"){
            if(Pop(Stack)==true){
                cout<<"Element was successfully popped"<<endl;
                if(Top(Stack,top)==true){
                    cout<<"Top Element is:"<<top<<endl;
                }else{
                    cout<<"Stack is now Empty!"<<endl;
                }
            }else{
                cout<<"ERROR : Stack is empty!"<<endl;
            }
        }else if(instruction=="top"){
                if(Top(Stack,top)==true){
                    cout<<"Top Element is:"<<top<<endl;
                }else{
                    cout<<"ERROR : Stack is empty!"<<endl;
                }
        }else{
            cout<<"ERROR : Unknown operation! Please try again"<<endl;
        }
    }
    return 0;
}

以上是关于c_cpp 使用Vector PopBack进行堆栈实现的主要内容,如果未能解决你的问题,请参考以下文章

popBack 到选定选项卡的第一个视图控制器

c_cpp vector_de_vector.cpp

c_cpp vector_de_vector.cpp

C++ 初阶vecotr底层框架模拟实现

C++ 初阶vecotr底层框架模拟实现

c_cpp vector.h