#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class myVct
{
private:
T *first;
T *last;
T *end;
public:
//构造函数
myVct(int size = 2)
{
first = new T[size];
last = first; //为空
end = first+size; //空间尾指针
}
//析构函数
~myVct()
{
delete [] first;
first = last = end = NULL;
}
//拷贝构造
myVct(const myVct &other)
{
//计算原空间大小
int len = other.last - other.first;
int size = other.end - other.first;
this->first = new T[size];//新对象容量
memcpy(this->first,other.first,len*sizeof(T));
//将该对象的另外两个指针指向对应位置
this->last = this->first+len;
this->end = this->first+size;
}
//判空
bool empty()
{
return this->first == this->last;
}
//判满
bool full()
{
return this->last == this->end;
}
//二倍扩容
void greater()
{
//获取当前容器总容量
int size = this->end-this->first;
//在堆区申请二倍空间
T *temp = new T[2*size];
memcpy(temp,this->first,size*sizeof(T));
delete []first;
//更新指针指向
first = temp;
//更新其他指针指向
last = first+size;
end = first+2*size;
}
//尾插
void push_back(const T val)
{
//判满
if(this->full())
{
this->greater(); //满了二倍扩容
}
*last = val;
last++;
}
//尾删
void pop_back()
{
if(this->empty())
{
return;
}
//尾指针
--last;
}
//实现获取第一个元素
T front()const
{
return *last;
}
//计算元素个数
int size()
{
return end-first;
}
int len()
{
return last-first;
}
//at 函数
T&at(int index)
{
if(index < 0 || index > this->len())
{
cout<<"越界"<<endl;
}
return first[index];
}
};
int main()
{
myVct<int> v;
cout<<v.size()<<endl;
for(int i=0;i<20;i++)
{
v.push_back(i);
cout<<v.size()<<endl;
}
for(int i=0;i<20;i++)
{
cout<<v.at(i)<<" ";
}
cout<<endl;
cout << "Hello World!" << endl;
return 0;
}
2
2
2
4
4
8
8
8
8
16
16
16
16
16
16
16
16
32
32
32
32
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Hello World!