程序:
#include <iostream>
using namespace std;
template <typename T>
class my_vector
{
private:
T *first;
T *last;
T *end;
public:
my_vector(){first=nullptr,last=nullptr,end=nullptr;}
my_vector(int m,T n)
{
first=new T[m];
for(int i=0;i<m;i++)
{
first[i]=n;
}
last=first+m;
end=first+m;
}
~my_vector()
{
delete []first;
first=end=last=nullptr;
cout<<"析构函数"<<endl;
}
//拷贝构造
my_vector(const my_vector & other)
{
int size = other.end-other.first;
first = new T[size];
end = first+size,last = end;
memcpy(first,other.first,sizeof(T)*size);
cout << "拷贝构造" << endl;
}
//拷贝赋值
my_vector<T> & operator=(const my_vector & other)
{
int my_size = size();
int ssize = other.end - other.first;
if(ssize>this->size())
{
T* p= new T[ssize];
memcpy(p,first,sizeof(T)*my_size);
delete []first;
first = p;
last = first+ssize;
end = last;
}
cout <<"拷贝赋值" << endl;
return *this;
}
//判满
bool full()
{
return end==last;
}
//判空
int empty()
{
return first==last ?1:0;
}
//按位置查找
T &at(int n)
{
if(empty())
{
cout<<"没有数据,查找失败"<<endl;
}
return first[n-1];
}
//查找第一个元素
T &front()
{
if(empty())
{
cout<<"没有数据,查找失败"<<endl;
}
return first[0];
}
//查找最后一个元素
T &back()
{
return *(last-1);
}
int size()
{
return last-first;
}
//扩容后的容量
int capacity()
{
return end-first;
}
//清空
void clear()
{
end=last=first;
}
//二倍扩容
void expand()
{
if(full()){
int size1=size();
T *p=new T[size1*2];
for(int i=0;i<size1;i++)
{
p[i]=first[i];
}
delete []first;
first=p;
last=first+size1;
end=first+size1*2;
}
}
//push_back
void push_back(T a)
{
if(empty())
{
first=new T[2];
*(first)=a;
last=first;
end=first+1;
}
else
{
expand();
*(last)=a;
last++;
cout<<"插入成功"<<endl;
}
}
//pop_back
void pop_back()
{
last--;
cout<<"删除成功"<<endl;
}
void show()
{
for(T* i=first;i!=last;i++)
{
cout << *i << " capacity="<<capacity()<<endl;;
}
}
};
int main()
{
//有参构造
my_vector<int> v1(5,3);
v1.show();
//第一位元素
cout<<"第一位元素"<<v1.front()<<endl;
//删除
v1.pop_back();
v1.show();
//插入
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(3);
v1.push_back(3);
v1.push_back(4);
v1.push_back(5);
v1.push_back(5);
v1.push_back(5);
v1.show();
//最后一位元素
cout<<"最后一个元素"<<v1.back()<<endl;
//按位置查找
cout<<"第八位元素"<<v1.at(8)<<endl;
return 0;
}
运行效果: