|
只实现了push_back pop_back begin end等方法,其他的方法没有写
#include <iostream>
using namespace std;
template<typename T>
class Myarray{
public:
Myarray();
void push_back(T);
void pop_back();
T operator [](int);
typedef T* iterator;
iterator begin();
iterator end();//返回值是指向最后一个元素后面的位置,而不是指向最后一个元素的位置
private:
T* pt;
int currentcount;
int maxcount;
};
template<typename T>
Myarray<T>::Myarray(){
pt=new T[10];
currentcount=0;
maxcount=10;
}
template<typename T>
void Myarray<T>::push_back(T kt){
if(currentcount<maxcount){
pt[currentcount]=kt;
++currentcount;
}else{
T* tempt=new T[2*maxcount];
memcpy(tempt,pt,currentcount*sizeof(T));
tempt[currentcount]=kt;
delete[] pt;
pt=tempt;
++currentcount;
maxcount*=2;
}
}
template<typename T>
void Myarray<T>::pop_back(){
--currentcount;
}
template<typename T>
T Myarray<T>::operator [](int n){
return pt[n];
}
template<typename T>
typename Myarray<T>::iterator Myarray<T>::begin(){
return pt;
}
template<typename T>
typename Myarray<T>::iterator Myarray<T>::end(){
return pt+currentcount;
}
int main(int argc, char** argv) {
Myarray<int> ceshi;
for(int i=0;i<10;++i)
ceshi.push_back(i);
for(Myarray<int>::iterator i=ceshi.begin();i!=ceshi.end();++i){
cout<<*i<<endl;
}
cout<<"==================="<<endl;
for(int i=0;i<10;++i)
ceshi.push_back(i*2);
for(Myarray<int>::iterator i=ceshi.begin();i!=ceshi.end();++i){
cout<<*i<<endl;
}
cout<<"==================="<<endl;
ceshi.pop_back();
for(Myarray<int>::iterator i=ceshi.begin();i!=ceshi.end();++i){
cout<<*i<<endl;
}
cout<<"==================="<<endl;
cout<<"测试[]重载"<<"\t"<<ceshi[5]<<endl;
cout<<"==================="<<endl;
Myarray<char*> cschar;
cschar.push_back("ceshi");
cschar.push_back("水电费");
cschar.push_back("234");
cschar.push_back("sdf333");
cschar.push_back("参数df3");
for(Myarray<char*>::iterator i=cschar.begin();i!=cschar.end();++i){
cout<<*i<<endl;
}
cout<<"==================="<<endl;
cschar.pop_back();
for(Myarray<char*>::iterator i=cschar.begin();i!=cschar.end();++i){
cout<<*i<<endl;
}
cout<<"==================="<<endl;
system("pause");
return 0;
}
|
|