现在的位置: 首页 > 综合 > 正文

动态数组c++

2013年10月01日 ⁄ 综合 ⁄ 共 1753字 ⁄ 字号 评论关闭

#include <iostream>
using namespace std;

//默认情况下动态数组的长度为2

template <class DataType>
class Array
{
public:
 Array(int size = 2);
 Array(const Array<DataType> &copy);
 Array<DataType>& operator=(const Array<DataType> &right);
 ~Array();
 DataType &operator[](int index);
 void ChangeSize(int size);
 int GetSize()const;
private:
 inline void DeepCopy(const Array<DataType> &origin);
 DataType *element;
 int capacity;
};

template< class DataType>
Array<DataType>::Array(int size)
{
 if(size < 1)
 {
       capacity = 2;
 }
 else
 {
  capacity = size;
 }
 element = new DataType[capacity];
}

template <class DataType>
Array<DataType>::Array(const Array<DataType> &copy)
{
 DeepCopy(copy);
}

template <class DataType>
Array<DataType>& Array<DataType>::operator=(const Array<DataType> &right)
{
 if(this == &right)
 {
  return *this;
 }
 delete []element;
 DeepCopy(right);
 return *this;
}

template <class DataType>

Array<DataType>::~Array()
{
 delete []element;
}

template < class DataType>
DataType& Array<DataType>::operator[](int index)
{

 return element[index];
}

template <class DataType>
void Array<DataType>::ChangeSize(int size)
{
 if((size<1) || (size==capacity))
 {
  return;
 }
 DataType *newelement = new DataType[size];
 int limit = (size>capacity) ? capacity : size;
 for(int i=0; i<limit; i++)
 {
  newelement[i] = element[i];
 }
 delete []element;
 element = newelement;
 capacity = size;
}

template<class DataType>
inline void Array<DataType>::DeepCopy(const Array<DataType> &origin)
{
 capacity = origin.capacity;
 for(int i=0; i<capacity; i++)
 {
  element[i] = origin.element[i];
 }
}

template<class DataType>
int Array<DataType>::GetSize()const
{
 return capacity;
}
int main()
{
 Array<int> arr(20);
 for(int i=0; i<20; i++)
 {
  arr[i] = i;
 }
 for(int j=0; j<20; j++)
 {
  cout<<"  "<<arr[j];
 }
 cout<<endl;
 arr.ChangeSize(arr.GetSize()<<1);
 for(int m=20; m<40; m++)
 {
  arr[m] = m;
 }
 for(int k=0; k<40; k++)
 {
  cout<<"  "<<arr[k];
 }

 cout<<endl;
 return 0;
}

抱歉!评论已关闭.