C++语言实现线性表之数组实例
本文实例讲述了C++语言实现线性表之数组。分享给大家供大家参考。具体分析如下:
感觉用C++中的构造函数、析构函数等类的特点来描述一些数据结构更加易读,更加合理,便捷。但有一个问题,编译器不支持模板的分离编译,很不舒服
#include<iostream>
usingnamespacestd;
template<classT>
classCArray
{
public:
CArray(constint&iMax);
CArray();
~CArray();
voidCreate(constint&iMax);
voidDestroy();
voidPrint();
boolIsEmpty();
boolIsFull();
voidAppend(constT&data);
intGetLength();
intGetMax();
boolDelete(constint&pos);
boolInsert(constint&pos,constT&data);
voidoperator+=(constT&data);
private:
T*m_pArray;
intm_len;
intm_max;
voidReset();
};
template<classT>
CArray<T>::CArray(constint&iMax)
{
Create(iMax);
}
template<classT>
CArray<T>::~CArray()
{
Destroy();
}
template<classT>
voidCArray<T>::Create(constint&iMax)
{
m_pArray=newT[iMax];
m_max=iMax;
m_len=0;
memset(m_pArray,0,sizeof(m_pArray));
}
template<classT>
voidCArray<T>::Destroy()
{
delete[]m_pArray;
}
template<classT>
voidCArray<T>::Print()
{
if(IsEmpty())
{
cout<<"没有数据!"<<endl;
}
else
{
for(intix=0;ix<m_len;++ix)
{
cout<<m_pArray[ix]<<",";
}
cout<<endl;
}
}
template<classT>
boolCArray<T>::IsEmpty()
{
if(0==m_len)
{
returntrue;
}
else
{
returnfalse;
}
}
template<classT>
boolCArray<T>::IsFull()
{
if(m_len==m_max)
{
Reset();
returnfalse;
}
else
{
returnfalse;
}
}
template<classT>
voidCArray<T>::Append(constT&data)
{
if(!IsFull())
{
++m_len;
m_pArray[m_len-1]=data;
}
}
template<classT>
intCArray<T>::GetLength()
{
returnm_len;
}
template<classT>
boolCArray<T>::Delete(constint&pos)
{
if(pos>m_len||pos<=0)
{
cout<<"位置不合法"<<endl;
returnfalse;
}
for(intix=pos-1;ix<m_len-1;++ix)
{
m_pArray[ix]=m_pArray[ix+1];
}
--m_len;
returntrue;
}
template<classT>
voidCArray<T>::operator+=(constT&data)
{
this->Append(data);
}
template<classT>
boolCArray<T>::Insert(constint&pos,constT&data)
{
if(IsFull())
{
returnfalse;
}
else
{
for(intix=m_len-1;ix>=pos-1;--ix)
{
m_pArray[ix+1]=m_pArray[ix];
}
m_pArray[pos-1]=data;
++m_len;
returntrue;
}
}
template<classT>
CArray<T>::CArray()
{
Create(5);
}
template<classT>
voidCArray<T>::Reset()
{
T*pT=newT[m_max*2];
memset(pT,0,sizeof(pT));
for(intix=0;ix<m_len;++ix)
{
pT[ix]=m_pArray[ix];
}
delete[]m_pArray;
m_pArray=pT;
m_max=m_max*2;
}
template<classT>
intCArray<T>::GetMax()
{
returnm_max;
}
希望本文所述对大家的C++程序设计有所帮助。