以前学习STL时练手写的一个简陋版vector
无意中翻到以前学习STL时练手写的简陋版vector,只实现了push_backpop_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;
currentcount=0;
maxcount=10;
}
template<typename T>
void Myarray<T>::push_back(T kt){
if(currentcount<maxcount){
pt=kt;
++currentcount;
}else{
T* tempt=new T;
memcpy(tempt,pt,currentcount*sizeof(T));
tempt=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;
}
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<<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;
}
大佬大佬
页:
[1]