stack使用与简单实现

来源:互联网 发布:网络空间安全专业排名 编辑:程序博客网 时间:2024/06/08 17:22

1)首先介绍下Satck的使用

#include"stdafx.h"

#include<stack>

#include<list>

#include<iostream>

usingnamespacestd;


intmain()

{

stack<int,list<int>>iStack;

iStack.push(1);//进行数据的压入

iStack.push(4);

iStack.push(7);

iStack.push(15);

iStack.push(11);

iStack.push(9);

iStack.push(4);

iStack.push(6);


cout<<iStack.size()<<endl;//测试大小

cout<<iStack.top()<<endl;//获取顶部数据


for(size_ti=0;i<iStack.size();++i)

{

iStack.pop();//弹出数据

cout<<iStack.top()<<" ";//数据的获取

}

cout<<endl;

getchar();

return0;

}


2)进行Stack的编写 由于SGISTL源码没有提供泛型指针(其实也没必要呵呵)这里简单使用下泛型指针,以供参考

#include"stdafx.h"

#include<iostream>

usingnamespacestd;


template<classT>

classStack

{

public:

typedefT*iterator;

typedefT&reference;

typedefconstT*const_iterator;

typedefconstT&const_reference;

private:

T*arr;

inttop;//栈顶指针

iteratorm_top;//同步于栈顶指针使得泛型好使

iteratorm_bot;//尾部指针不动的

size_tmaxSize;

conststaticsize_tmaxSatckSize= 40; //定义最大的存储量


public:

Stack():top(-1),arr(NULL),maxSize(maxSatckSize)

{

arr=newT[maxSize];

m_bot=arr;

m_top=m_bot;

}


Stack(size_tsize):top(-1),arr(NULL),maxSize(maxSatckSize)

{

maxSize=size>maxSize?maxSize:size;

arr=newT[maxSize];

m_bot=arr;

m_top=m_bot;

}

~Stack(){if(arr)delete[]arr;}//进行内存的释放

voidsetEmpty()//设置为空

{

top= -1;

}

iteratorgetBegin()

{

returnm_bot;

}

iteratorgetEnd()

{

returnm_top;

}

voidIsEmpty()

{

return(top==-1);

}

voidIsFull()

{

return(top==maxSize-1);//如果再次追加内存时应该将maxSize进行相应的增加

}

const_referencegetTop()const//获取头结点

{

returnarr[top];

}

voidpush(constT&val)

{

if(top+1==maxSize)

extendArr(2*maxSize);

arr[++top]=val;

m_top++;

}


voidextendArr(size_tsize)

{

T*oldArr=arr;//将旧的赋值给新的

arr=newT[size];

for(size_ti=0;i<maxSize;i++)

arr[i]=oldArr[i];

maxSize=size;

delete[]oldArr;

}


referencepop()

{

top--;

m_top--;

returnarr[top];

}


constStack&operator=(constStack&src)

{

if(this== &src)return*this;

delete[]arr;

arr=newT[src.maxSize];

top=src.top;

for(size_ti=0;i<=top;i++)

arr[i]=src.arr[i];

return*this;

}


voidoperator++()

{

if(top+1==maxSize)

throwout_of_range("数据空间受限!");

top++;

m_top++;

}


voidoperator--()

{

if(top== -1)

return;

top--;

m_top--;

}


booloperator==(constStack<T>&com)const

{return(*this==com);}


booloperator!=(constStack<T>&com)const

{return(!(*this==com));}


booloperator<(constStack<T>&com)const

{return(*this<com);}


booloperator>(constStack<T>&com)const

{return(com< *this);}


booloperator<=(constStack<T>&com)const

{return(!(com< *this));}


booloperator>=(constStack<T>&com)const

{return!(*this<com);}

};


int_tmain(intargc,_TCHAR*argv[])

{

Stack<int>stack;

stack.push(-1);

stack.push(2);

stack.push(0);

stack.push(3);

stack.push(5);

stack.push(6);

stack.push(7);

for(Stack<int>::iteratorit=stack.getBegin();it<stack.getEnd();it++)//使用泛型指针

cout<<*it<<" ";

getchar();

return0;

}



0 0
原创粉丝点击