要求:
#include <iostream>
#include <string.h>
using namespace std;
template <typename T>
class myVector{
private:
T *begin;
T *last;
T *end;
public:
myVector(){}
myVector(int num,const T &c)
{
int n=0;
if(num<=16)
{
n=16;
}
else{
n=16*(num/16+1);
}
begin=new T[n];
last=begin;
end=begin+n;
for(int i=0;i<num;i++)
{
*(begin+i)=c;
last++;
}
}
~myVector()
{
delete []begin;
}
myVector(const myVector &other)
{
this->begin=new T[other.end-other.begin];
last=begin;
for(int i=0;i<(other.last-other.begin);i++)
{
*(begin+i)=*(other.begin+i);
last++;
}
end=begin+(other.end-other.begin);
}
myVector &operator=(const myVector &other)
{
this->begin=new T[other.end-other.begin];
last=begin;
for(int i=0;i<(other.last-other.begin);i++)
{
*(begin+i)=*(other.begin+i);
last++;
}end=begin+(other.end-other.begin);
}
T at(int num)
{
T *p=begin;
for(int i=0;i<num;i++)
{
p++;
}
return *p;
}
bool empty()
{
return last==begin;
}
bool full()
{
return last==end;
}
T front()
{
return *begin;
}
T back()
{
return *(last-1);
}
int size()
{
return last-begin;
}
void clear()
{
last=begin;
}
T capicity()
{
return (end-begin);
}
void expand()
{
if(full())
{
T *p;
p=new T[2*(end-begin)];
int n=last-begin;
for(int i=0;i<(last-begin);i++)
{
*(p+i)=*(begin+i);
}
begin=p;
last=begin+n;
end=begin+2*n;
}
}
void push_back(int data)
{
if(last-begin<=16)
{
end=begin+16;
}
*last=data;
last++;
if(full())
{
expand();
}
}
void pop_back()
{
if(empty())
{
cout<<"容器为空,尾删失败"<<endl;
}
else
{
last=last-1;
}
}
};
int main()
{
myVector<int> v1(5,1);
cout<<"v1的size:"<<v1.size()<<endl;
v1.push_back(6);
cout<<"front():"<<v1.front()<<" "<<"back():"<<v1.back()<<endl;
cout<<"capiticy():"<<v1.capicity()<<endl;
for(int i=0;i<10;i++)
{
v1.push_back(6);
}
cout<<"size():"<<v1.size()<<" "<<"capiticy():"<<v1.capicity()<<endl;
myVector<int> v2;
v2=v1;
cout<<"size:"<<v2.size()<<endl<<"capicity:"<<v2.capicity()<<endl;
return 0;
}