c++模板實現(xiàn)棧

棧的管理可以用運鏈表,當(dāng)然啦也可以用運數(shù)組,相比鏈表而數(shù)組管理起來更加方便,為什么呢???請睜大眼睛看下邊博主大人的總結(jié)
數(shù)組管理棧的優(yōu)點:
(1)插入刪除方便,數(shù)組直接將++_top或者--_top即可,而鏈表還要刪除節(jié)點置空指針,麻煩死啦;
(2)效率高呀,數(shù)組一次能夠new T [_capacity]省事,而鏈表邊用邊new;
(3)其實這里還牽扯到一個cpu的高速緩存利用率

c++模板實現(xiàn)棧

成都創(chuàng)新互聯(lián)公司長期為近1000家客戶提供的網(wǎng)站建設(shè)服務(wù),團隊從業(yè)經(jīng)驗10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為寧縣企業(yè)提供專業(yè)的成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè),寧縣網(wǎng)站改版等技術(shù)服務(wù)。擁有十年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。

static and queue.h

#pragma  once

#include<iostream>

using namespace std;

template<class T>

class stack

{

public:

    stack()

:_a(0)

,_top(0)

,_capacity(0)

{}

   //剛開始寫這個函數(shù)的時候很傻比,哎,下次一定銘記

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;

}

}

//棧擴容函數(shù)

void _checkcapacity()

{

//不能用realloc開辟因為它不會調(diào)用構(gòu)造和析構(gòu)函數(shù)

              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;

};

static and queue.cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include"stack and queue.h"
#include<assert.h>
using namespace std;

template<class T>
void stack<T>::print()
{
	while(!empty())
	{
	cout<<_top<<" ";
	pop();
	}
	cout<<"over"<<endl;;
}

template<class T>
void stack<T>::push(const T& x)
{
   _checkcapacity();
   _a[_top++]=x;
}

template<class T>
void stack<T>::pop()
{
	if(_top>0)
	{
		--_top;
	}
}
template<class T>
T& stack<T>::top()
{
	if(!empty())
	{
	return _a[_top-1];
	}
}

template<class T>
bool stack<T>::empty()
{
	return (_top==0);
}


void TestStack()
{
   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;*/
}
int main()
{
	TestStack();
	system("pause");
	return 0;
}

c++模板實現(xiàn)棧

文章題目:c++模板實現(xiàn)棧
路徑分享:http://muchs.cn/article16/ijddgg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、定制開發(fā)企業(yè)網(wǎng)站制作、靜態(tài)網(wǎng)站品牌網(wǎng)站設(shè)計、品牌網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)