C++栈的用法及栈的实现

  1. 首先看一下原c++栈的方法的基本用法:
    1. push(): 向栈内压入一个成员;
    2. pop(): 从栈顶弹出一个成员;
    3. empty(): 如果栈为空返回true,否则返回false;
    4. top(): 返回栈顶,但不删除成员;
    5. size(): 返回栈内元素的大小;
  2. 代码示例:
#include<iostream>
#include<stack>
using namespace std;

int main()
{
    stack <int>stk;
    //入栈
    for(int i=0;i<50;i++){
        stk.push(i);
    }
    cout<<"栈的大小:"<<stk.size()<<endl;
    while(!stk.empty())
    {
        cout<<stk.top()<<endl;
        stk.pop();
    }
    cout<<"栈的大小:"<<stk.size()<<endl;
    return 0;
}

  1. 接下来我们自己写栈,这时就需要用到c++中的模板类(template)
#include<iostream>
#include<stdlib.h>
using namespace std;

#define MAXSIZE 0xffff

template<class type>
class my_stack
{
    int top;
    type* my_s;
    int maxsize;

public:
    my_stack():top(-1),maxsize(MAXSIZE)
    {
        my_s=new type[maxsize];
        if(my_s==NULL)
        {
            cerr<<"动态存储分配失败!"<<endl;
            exit(1);
        }
    }
    my_stack(int size):top(-1),maxsize(size)
    {
        my_s=new type[maxsize];
        if(my_s==NULL)
        {
            cerr<<"动态存储分配失败!"<<endl;
            exit(1);
        }
    }
    ~my_stack()
    {
        delete[] my_s;
    }
    //是否为空
    bool Empty();
    //压栈
    void Push(type tp);
    //返回栈顶元素
    type Top();
    //出栈
    void Pop();
    //栈大小
    int Size();
};

template<class type>
bool my_stack<type>::Empty()
{
    if(top==-1){
        return true;
    }
    else
        return false;
}

template<class type>
type my_stack<type>::Top()
{
    if(top!=-1)
    {
        return my_s[top];
    }
    else
    {
        cout<<"栈空\n";
        exit(1);
    }
}

template<class type>
void my_stack<type>::Push(type tp)
{
    if(top+1<maxsize)
    {
        my_s[++top]=tp;
    }
    else
    {
        cout<<"栈满\n";
        exit(1);
    }
}

template<class type>
void my_stack<type>::Pop()
{
    if(top>=0)
    {
        top--;
    }
    else
    {
        cout<<"栈空\n";
        exit(1);
    }
}

template<class type>
int my_stack<type>::Size()
{
    return top+1;
}

  1. 然后就可以在另一个cpp文件中使用它了(记得include):
#include<iostream>
#include "my_stack.cpp"

using namespace std;

int main()
{
    my_stack<int> stk;
    for(int i=0;i<50;i++){
        stk.Push(i);
    }
    cout<<"栈的大小:"<<stk.Size()<<endl;
    while(!stk.Empty())
    {
        cout<<stk.Top()<<endl;
        stk.Pop();
    }
    cout<<"栈的大小:"<<sizeof(stk)<<endl;
    return 0;
}
  1. 在编写代码的时候我突然很好奇,size()和sizeof输出的区别,然后我用我写的栈做了尝试:
#include<iostream>
#include<stack>
#include "my_stack.cpp"

using namespace std;

int main()
{
    my_stack<int> stk;
    stack<int> s;
    for(int i=0;i<20;i++){
        stk.Push(i);
        s.push(i);
    }
    cout<<"mysize()="<<stk.Size()<<"\nmysizeof="<<sizeof(stk)<<endl;
    cout<<"size()="<<s.size()<<"\nsizeof="<<sizeof(s)<<endl;
    return 0;
}

输出:
mysize()=20
mysizeof=12
size()=20
sizeof=40

并且可以看到我写的栈类的变量只有三个整型(一个template型),刚好12个字节,由此可知c++提供的栈内不止我写的这么简单,光变量就占40个字节

猜你喜欢

转载自blog.csdn.net/qq_20366761/article/details/70053813
今日推荐