C++語言實現(xiàn)線性表之數(shù)組實例
更新時間:2015年04月20日 11:14:50 作者:司青
這篇文章主要介紹了C++語言實現(xiàn)線性表之數(shù)組,實例分析了C++實現(xiàn)數(shù)組形式線性表的原理與方法,需要的朋友可以參考下
本文實例講述了C++語言實現(xiàn)線性表之數(shù)組。分享給大家供大家參考。具體分析如下:
感覺用C++中的構(gòu)造函數(shù)、析構(gòu)函數(shù)等類的特點來描述一些數(shù)據(jù)結(jié)構(gòu)更加易讀,更加合理,便捷。但有一個問題,編譯器不支持模板的分離編譯,很不舒服
#include <iostream>
using namespace std;
template<class T>
class CArray
{
public:
CArray(const int &iMax);
CArray();
~CArray();
void Create(const int &iMax);
void Destroy();
void Print();
bool IsEmpty();
bool IsFull();
void Append(const T &data);
int GetLength();
int GetMax();
bool Delete(const int &pos);
bool Insert(const int &pos,const T &data);
void operator+=(const T &data);
private:
T *m_pArray;
int m_len;
int m_max;
void Reset();
};
template<class T>
CArray<T>::CArray(const int &iMax)
{
Create(iMax);
}
template<class T>
CArray<T>::~CArray()
{
Destroy();
}
template<class T>
void CArray<T>::Create(const int &iMax)
{
m_pArray = new T[iMax];
m_max = iMax;
m_len = 0;
memset(m_pArray,0,sizeof(m_pArray));
}
template<class T>
void CArray<T>::Destroy()
{
delete [] m_pArray;
}
template<class T>
void CArray<T>::Print()
{
if(IsEmpty())
{
cout<<"沒有數(shù)據(jù)!"<<endl;
}
else
{
for(int ix =0 ; ix < m_len ; ++ix)
{
cout<<m_pArray[ix]<<",";
}
cout<<endl;
}
}
template<class T>
bool CArray<T>::IsEmpty()
{
if(0 == m_len)
{
return true;
}
else
{
return false;
}
}
template<class T>
bool CArray<T>::IsFull()
{
if(m_len == m_max)
{
Reset();
return false;
}
else
{
return false;
}
}
template<class T>
void CArray<T>::Append(const T &data)
{
if(!IsFull())
{
++m_len;
m_pArray[m_len - 1] = data;
}
}
template<class T>
int CArray<T>::GetLength()
{
return m_len;
}
template<class T>
bool CArray<T>::Delete(const int &pos)
{
if(pos > m_len || pos <= 0)
{
cout<<"位置不合法"<<endl;
return false;
}
for(int ix = pos - 1 ; ix < m_len - 1 ; ++ ix)
{
m_pArray[ix] = m_pArray[ix + 1];
}
--m_len;
return true;
}
template<class T>
void CArray<T>::operator+=(const T &data)
{
this->Append(data);
}
template<class T>
bool CArray<T>::Insert(const int &pos,const T &data)
{
if(IsFull())
{
return false;
}
else
{
for(int ix = m_len - 1 ; ix >= pos - 1 ; -- ix)
{
m_pArray[ix + 1] = m_pArray[ix];
}
m_pArray[pos - 1] = data;
++m_len;
return true;
}
}
template<class T>
CArray<T>::CArray()
{
Create(5);
}
template<class T>
void CArray<T>::Reset()
{
T *pT = new T[m_max * 2];
memset(pT,0,sizeof(pT));
for(int ix = 0 ; ix < m_len ; ++ ix)
{
pT[ix] = m_pArray[ix];
}
delete [] m_pArray;
m_pArray = pT;
m_max = m_max * 2;
}
template<class T>
int CArray<T>::GetMax()
{
return m_max;
}
希望本文所述對大家的C++程序設(shè)計有所幫助。
相關(guān)文章
C語言數(shù)據(jù)結(jié)構(gòu)順序表的進階講解
程序中經(jīng)常需要將一組數(shù)據(jù)元素作為整體管理和使用,需要創(chuàng)建這種元素組,用變量記錄它們,傳進傳出函數(shù)等。一組數(shù)據(jù)中包含的元素個數(shù)可能發(fā)生變化,順序表則是將元素順序地存放在一塊連續(xù)的存儲區(qū)里,元素間的順序關(guān)系由它們的存儲順序自然表示2022-04-04

