#include <iostream>
using namespace std;
template <typename T>
class My_vector
{
private:
T * first; //指向第一个元素
T * last; //指向最后一个元素
T * end; //指向容器末尾
public:
//构造函数
My_vector()
{
first = last = end = nullptr;
}
My_vector(int size = 8) //默认初始大小为8
{
first = new T[size]; //堆区申请空间
last = first; //初始为空
end = first + size; //容器末尾指针
}
//析构函数
~My_vector()
{
delete []first; //释放堆区空间
first = last = end = nullptr; //指针指向空
}
//拷贝构造
My_vector(const My_vector &other)
{
int size = other.end - other.first; //原始容器大小
this->first = new T[size]; //创建新容器
this->end = this->first + size; //定位新end指针
this->last = this->first + (other.last - other.first); //定位新last指针
}
//拷贝赋值
My_vector &operator=(const My_vector &other)
{
delete []this->first; //删除原始空间
int size = other.end - other.first; //原始容器大小
this->first = new T[size]; //创建新容器
this->end = this->first + size; //定位新end指针
this->last = this->first + (other.last - other.first); //定位新last指针
return *this;
}
//按位查找
T at(int n)
{
return this->first[n];
}
//判空函数
bool empty()
{
return this->first == this->last;
}
//判满函数
bool full()
{
return this->last == this->end;
}
//获取第一个元素
T &front()
{
return *first;
}
//获取最后一个元素
T &back()
{
return *(last-1);
}
//获取数据长度
int size()
{
return last-first;
}
//清空元素,容量不变
void clear()
{
last = first;
}
//二倍扩容
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;
end = first + 2*size;
}
//实现尾插
void push_back( const T val)
{
if(this->full())
{
this->expand(); //满了进行扩容
}
*last = val;
last++;
}
//实现尾删
void pop_back()
{
if(this->empty())
{
return;
}
--last;
}
};
int main()
{
My_vector<int> v1(12); //调用无参构造,数据元素类型为int类型
//判断当前数组是否为空
if(v1.empty())
{
cout<<"v1 is empty"<<endl;
}else
{
cout<<"v1 is not empty"<<endl;
}
//输出当前的数组容器的大小
cout<<"v1.size = "<<v1.size()<<endl;
//向容器中放入数据
for(int i=0; i<20; i++)
{
v1.push_back(520+i); //向末尾放入一个值
cout<<"v1.size = "<<v1.size()<< endl;
}
//遍历所有元素
for(int i=0; i<v1.size(); i++)
{
cout<<v1.at(i)<<" ";
}
cout<<endl;
//删除最后一个元素
v1.pop_back();
for(int i=0; i<v1.size(); i++)
{
cout<<v1.at(i)<<" ";
}
cout<<endl;
//第一个元素和最后一个元素
v1.front() = 0;
v1.back() = 99999;
for(int i=0; i<v1.size(); i++)
{
cout<<v1.at(i)<<" ";
}
cout<<endl;
//清空容器
v1.clear();
cout<<"v1.size = "<<v1.size()<<endl;
return 0;
}