c++语言 数组,C++语言实现线性表之数组实例

本文实例讲述了C++语言实现线性表之数组。分享给大家供大家参考。具体分析如下:

感觉用C++中的构造函数、析构函数等类的特点来描述一些数据结构更加易读,更加合理,便捷。但有一个问题,编译器不支持模板的分离编译,很不舒服

#include

using namespace std;

template

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

CArray::CArray(const int &iMax)

{

Create(iMax);

}

template

CArray::~CArray()

{

Destroy();

}

template

void CArray::Create(const int &iMax)

{

m_pArray = new T[iMax];

m_max = iMax;

m_len = 0;

memset(m_pArray,0,sizeof(m_pArray));

}

template

void CArray::Destroy()

{

delete [] m_pArray;

}

template

void CArray::Print()

{

if(IsEmpty())

{

cout<

}

else

{

for(int ix =0 ; ix < m_len ; ++ix)

{

cout<

}

cout<

}

}

template

bool CArray::IsEmpty()

{

if(0 == m_len)

{

return true;

}

else

{

return false;

}

}

template

bool CArray::IsFull()

{

if(m_len == m_max)

{

Reset();

return false;

}

else

{

return false;

}

}

template

void CArray::Append(const T &data)

{

if(!IsFull())

{

++m_len;

m_pArray[m_len - 1] = data;

}

}

template

int CArray::GetLength()

{

return m_len;

}

template

bool CArray::Delete(const int &pos)

{

if(pos > m_len || pos <= 0)

{

cout<

return false;

}

for(int ix = pos - 1 ; ix < m_len - 1 ; ++ ix)

{

m_pArray[ix] = m_pArray[ix + 1];

}

--m_len;

return true;

}

template

void CArray::operator+=(const T &data)

{

this->Append(data);

}

template

bool CArray::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

CArray::CArray()

{

Create(5);

}

template

void CArray::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

int CArray::GetMax()

{

return m_max;

}

希望本文所述对大家的C++程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值