自定义动态模版数组
#include <iostream>
using namespace std;
template <class T>
class CDynamicArray {
T *pData;
int nExistedNum;
int nMaxNum;
public:
CDynamicArray();
CDynamicArray(int n);
virtual ~CDynamicArray();
void traverse();
void push_back(T m);
void push_front(T m);
};
template <class T>
CDynamicArray<T> :: CDynamicArray() {
int n = 10;
pData = new T[n];
nExistedNum = 0;
nMaxNum = n;
}
template <class T>
CDynamicArray<T> :: CDynamicArray(int n) {
pData = new T[n];
nExistedNum = 0;
nMaxNum = n;
}
template <class T>
void CDynamicArray<T> ::push_back(T m) {
if(nExistedNum>nMaxNum-1){
T *pDataTemp = new T[nMaxNum + 10];
for (int i=0; i<nMaxNum; i++) {
pDataTemp[i]= pData[i];
}
delete pData;
nMaxNum += 10;
pData = pDataTemp;
}
pData[nExistedNum] = m;
nExistedNum++;
}
template <class T>
void CDynamicArray<T>::push_front(T m){
if (nExistedNum>nMaxNum-1) {
T *pDataTemp = new T[nMaxNum + 10];
for (int i=0; i<nMaxNum; i++) {
pDataTemp[i]=pData[i];
}
delete pData;
nMaxNum += 10;
pData = pDataTemp;
}
for (int i = nExistedNum; i>=0; i--) {
pData[i+1] = pData[i];
pData[0] = m;
nExistedNum++;
}
}
template <class T>
void CDynamicArray<T>::traverse() {
for (int i=0; i<nExistedNum; i++) {
cout<<pData[i];
}
cout<<endl;
}
验证
int main(int argc, const char * argv[]) {
CDynamicArray<int> array;
for (int i=0; i<20; i++) {
array.push_back(i);
}
array.traverse();
array.push_front(100);
array.traverse();
return 0;
}