#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
class vector
{
public:
T* first;
T* last;
T* end;
//无参构造
vector():first(NULL),last(NULL),end(NULL)
{
}
//有参构造
vector(int n,const T &val)
{
first = new T[n];
last = first + n;
end = first + n;
for(int i=0;i<n;i++)
{
*(first+i)=val;
}
}
vector( const T* s, const T* end2)
{
first = new T[end2-s];
end = first+(end2-s);
last = first;
for(int i=0;i<(end2 - s);i++)
{
*last=*(s+i);
last++;
}
}
int size()//输出大小
{
if(NULL == first)
return 0;
else
return last - first;
}
int capacity() //输出容器最大容量
{
if(NULL == first)
return 0;
else
return end - first;
}
void push_back(const T &val)//尾插
{
if(first == NULL)//判断是否是空
{
first = new T ;
last = first;
end = first + 1;
}
if(last == end)
{
int s_ize = end-first;
T* temp = new T[2*s_ize];
memset(temp,0,2*sizeof(T)*s_ize);
memcpy(temp,first,sizeof(T)*s_ize);
delete []first;
first = temp;
last = first + s_ize;
end = first + 2*(s_ize);
}
*last = val;
last = last + 1;
}
void pop_back()//尾删
{
last--;
}
T & at(int num)//定位
{
return *(first+num);
}
};
int main()
{
vector<int> v1; //定义一个容器
cout<<"v1.size = "<<v1.size()<<endl; //输出容器的大小
cout<<"v1.capacity = "<<v1.capacity()<<endl; //输出容器的最大容量
cout<<"-------------------------------------------------------\n";
for(int i=1; i<=20; i++) //输入二十个数
{
v1.push_back(i);
cout<<"v1.size = "<<v1.size()<<" v1.capacity = "<<v1.capacity()<<endl;
//左边是当前容器的大小 右边是容器的最大容量
}
//输出当前vector中的内容
for(auto i=0; i<v1.size(); i++)
{
//cout<<v1[i]<<" ";
cout<<v1.at(i)<<" ";
}
cout<<endl;
return 0;
}
现象: