C++语言实现线性表之数组实例
2015-04-20 11:14
781 查看
本文实例讲述了C++语言实现线性表之数组。分享给大家供大家参考。具体分析如下:
感觉用C++中的构造函数、析构函数等类的特点来描述一些数据结构更加易读,更加合理,便捷。但有一个问题,编译器不支持模板的分离编译,很不舒服
#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<<"没有数据!"<<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++程序设计有所帮助。
您可能感兴趣的文章:
相关文章推荐
- C++语言实现线性表之链表实例
- C++语言实现指向函数的指针数组实例
- C语言线性表的顺序表示与实现实例详解
- 黑马程序员--数组的反射,反射的实现框架实例,配置文件加载
- 用线性时间复杂度实现找出数组中出现一次的元素
- java数据结构:线性表之数组实现
- 最大子数组问题-暴力求解-c++代码实现及运行实例结果
- 最大子数组--线性非递归实现
- 雇佣问题随机排列数组(permuteBySorting)-c++代码实现及运行实例结果
- 雇佣问题原址排列给定数组(randomize In Place)-c++代码实现及运行实例结果
- 线性表之数组实现栈结构
- 线性表--数组实现+模板+迭代器
- 一个JavaScript递归实现反转数组字符串的实例
- php实现数组重复数字统计实例
- 线性表之数组实现
- MyArrayList(数组线性表的实现)
- 用线性时间复杂度实现找出数组中出现一次的元素
- 最大子数组问题-暴力求解-c++代码实现及运行实例结果
- 雇佣问题随机排列数组(permuteBySorting)-c++代码实现及运行实例结果
- 雇佣问题原址排列给定数组(randomize In Place)-c++代码实现及运行实例结果