#include <iostream>
using namespace std;
template <typename T>
class Myvector
{
private:
T * first;//首
T * last;//当前参数位置
T * end;//尾
public:
//构造函数
Myvector()
{
//定义初始化长度
int size = 2;
this->first = new T[size];
//无数据,first=last
this->last = this->first;
//end指向最后
this->end = this->first + size;
};
//析构函数
virtual ~Myvector()
{
delete [] first;
first = nullptr;
last = nullptr;
end = nullptr;
}
//拷贝构造
Myvector(const Myvector &other)
{
//other的数据个数
int len = other.last-other.first;
//other的空间大小
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;
}
//拷贝赋值
const Myvector &operator=(const Myvector &other)
{
//other的数据个数
int len = other.last-other.first;
//other的空间大小
int size = other.end - other.first;
//释放旧空间
delete [] this->first;
//头指针指向新的空间
this->first = new T[size];
//数据拷贝
memcpy(this->first, other.first, len*sizeof(T));
//指针重新指向
this->last = this->first+len;
this->end = this->first+size;
}
//at():返回指定位置的元素
T & at(int pos)const
{
//判断下标是否合法
if(pos<0 || pos>last-first-1)
throw -1;
return *(this+pos);
}
//empty():判空
bool empty()
{
if(last-first)
return false;
else
return true;
}
//full():判满
bool full()
{
if(end-last==1)
return false;
else
return true;
}
//front():实现获取第一个元素
T & front()const
{
return *first;
}
//back():返回最末一个元素
T & back()const
{
//注意last指针指向的是最后一个元素的后面位置
return *(last-1);
}
//size():返回Vector中元素个数
int & size()const
{
return last-first;
}
//clear():删除当前vector中的所有元素
void clear()
{
for(int i=0;i<size();i++)
{
pop_back();
}
}
//expand():二倍扩容函数
void expand()
{
//获取空间大小
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-1;
end = first + 2*size;
}
//push_back():尾插
void push_back(const T val)
{
//如果已满先扩容
if(full())
expand();
//赋值、尾指针后移
*last = val;
last = last + 1;
}
//pop_back():尾删
void pop_back()
{
//如果为空不能删
if(this->empty())
throw -1;
//尾指针前移
last = last - 1;
}
};
C++实现动态数组
最新推荐文章于 2023-05-28 20:57:30 发布