仿照系统的vector,手动实现一个my_vector
#include <iostream>
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 = nullptr;
}
//拷贝构造函数
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;
}
//扩容原则:2倍扩容
void greater()
{
//获取当前容器总容量
int size = this->end - this->first;
//在堆区重新申请一个2倍的空间
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 *first;
}
int size()
{
return end-first;
}
int len()
{
return last-first;
}
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=1; i<=20; i++)
{
v.push_back(i);
cout<<v.size()<<endl;
}
for(int i=0; i<20; i++)
{
cout<<v.at(i)<<" ";
}
cout<<endl;
return 0;
}