c++模板实现栈
栈的管理可以用运链表,当然啦也可以用运数组,相比链表而数组管理起来更加方便,为什么呢???请睁大眼睛看下边博主大人的总结数组管理栈的优点:(1)插入删除方便,数组直接将++_top或者--_top即可,而链表还要删除节点置空指针,麻烦死啦;(2)效率高呀,数组一次能够newT[_capacity]省事,而链表边用边new;(3)其实这里还牵扯到一个cpu的高速缓存利用率
staticandqueue.h
#pragma once
#include<iostream>
using namespace std;
template<class T>
class stack
{
public:
stack()
:_a(0)
,_top(0)
,_capacity(0)
{}
//刚开始写这个函数的时候很傻比,哎,下次一定铭记
stack(const stack <T>& s)
:_a(new T[s._capacity])
,_top(s._top)
,_capacity(s._capacity)
{
int i=0;
for(i=0;i<s._top;i++)
{
_a[i]=s._a[i];
}
}
stack<T>& operator=(const stack<T>& s)
{
if(this!=&s)
{
delete [] _a;
_a=new T [s._capacity*sizeof(T)];
int i=0;
for(i=0;i<_top;i++)
{
a[i]=s._a[i];
}
_top=s._top;
_capacity=s._capacity;
}
return *this;
}
~stack()
{
if(_a!=NULL)
{
delete [] _a;
_a=NULL;
}
}
//栈扩容函数
void _checkcapacity()
{
//不能用realloc开辟因为它不会调用构造和析构函数
if(_top==_capacity)
{
_capacity=_capacity*2+3;
T* tmp=new T [_capacity];
int i=0;
for(i=0;i<_top;i++)
{
tmp[i]=_a[i];
}
delete [] _a;
_a=tmp;
}
}
void push(const T& x);
void pop();
T& top();
bool empty();
size_t size();
void print();
protected:
T * _a;
size_t _top;
size_t _capacity;
};
staticandqueue.cpp#define_CRT_SECURE_NO_WARNINGS1#include"stackandqueue.h"#include<assert.h>usingnamespacestd;template<classT>voidstack<T>::print(){while(!empty()){cout<<_top<<"";pop();}cout<<"over"<<endl;;}template<classT>voidstack<T>::push(constT&x){_checkcapacity();_a[_top++]=x;}template<classT>voidstack<T>::pop(){if(_top>0){--_top;}}template<classT>T&stack<T>::top(){if(!empty()){return_a[_top-1];}}template<classT>boolstack<T>::empty(){return(_top==0);}voidTestStack(){stack<int>s1;s1.push(1);s1.push(2);s1.push(3);s1.push(4);stack<int>s2(s1);stack<int>s3=s2;s1.print();s2.print();s3.print();/*cout<<s.top()<<endl;*/}intmain(){TestStack();system("pause");return0;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。