要实现的函数:
构造函数
析构函数
拷贝构造
拷贝赋值
at()
empty()
full()
front()
back()
size()
clear()
expand() 二倍扩容函数
push_back()
pop_back()
实现过程
#include <iostream>
using namespace std;
template <typename T>
class myvector
{
private:
T *first;
T *last;
T *end;
public:
myvector(){
this->first=new T[1];
last=first;
end=first;
};
myvector(T num,T val)
{
first=new T[num];
for(int i=0;i<num;i++)
{
*(first+i)=val;
}
last=first+num;
end=last;
}
myvector(myvector &R)
{
first=new T[R.end-R.first];
last=first+(R.last-R.first);
end=last;
for(int i=0;i<(R.last-R.first);i++)
{
*(first+i)=*(R.first+i);
}
}
~myvector()
{
delete []first;
};
void show()
{
for(int i=0;i<last-first;i++)
cout<<*(first+i)<<" ";
cout<<endl;
}
myvector &operator=(const myvector &o)
{
if(first==end)
{
end=first+1 ;
}
while (o.end-o.first>end-first) {
expand();
}
// this->first=new T(o.end-o.first);
this->last=this->first+(o.last-o.first);
for(int i=0;i<o.last-o.first;i++)
{
this->first[i]=o.first[i];
}
return *this;
}
T &at(int n)
{
return first[n];
}
bool empty()
{
return last-first;
}
bool full()
{
return end-first>0;
}
T &front()
{
return first;
}
T &back()
{
return last;
}
T size()
{
return last-first;
}
T clear()
{
last=first;
}
void expand()
{
T *temp=new T [2*(end-first)];
memcpy(temp,first,sizeof(T)*(end-first));
T t1=last-first;
T t2=2*(end-first);
delete []first;
first=temp;
last=first+t1;
end=first+t2;
}
void display()
{
cout<<"最大容量为"<<end-first<<endl;
}
void push_back(T n)
{
if(first==end)
{
end=first+1 ;
}
if(last==end)
{
expand();
}
if(full()!=0)
*last=n;
last++;
}
void pop_back()
{
if(empty()!=0)
last--;
}
};
int main()
{
myvector<int> m(5,7);
m.show();
myvector<int> m1(m);
m1.show();
myvector<int> m2;
m2=m;
m2.display();
m2.show();
m2.at(2)=5;
m2.show();
cout<<m2.at(2)<<endl;
m2.pop_back();
m2.show();
m2.push_back(9);
m2.show();
for(int i=0;i<20;i++)
{
m2.push_back(i);
m2.display();
}
return 0;
}
实验结果: