实现vector里函数功能:
#include <iostream>
using namespace std;
template <typename T>
class myvector
{
private:
T * first;
T * last;
T * end;
public:
//无参构造
//myvector() {cout<<"无参构造"<<endl;}
//有参构造
myvector():first(nullptr),last(nullptr),end(nullptr)
{
cout<<"有参构造"<<endl;
}
//析构函数
~myvector()
{
delete []first;
cout<<"析构函数"<<endl;
}
//拷贝构造
myvector(const myvector &other)
{
int length = other.size();
first = new T[length];
last = first + length;
end = last;
for(int i=0;i<length;i++)
{
first[i]=other.first[i];
}
cout<<"拷贝构造"<<endl;
}
//拷贝赋值
myvector &operator=(const myvector &other)
{
if(this != &other) //避免自己给自己赋值
{
int length = other.size();
first = new T[length];
last = first + length;
end = last;
for(int i=0;i<length;i++)
{
first[i]=other.first[i];
}
}
cout<<"拷贝赋值"<<endl;
return *this;
}
//获取指定下标的元素
T &at(int index)
{
return first[index];
}
//判断容器是否为空
bool empty()
{
return first==last;
}
//判断容器是否满
bool full()
{
return last==end;
}
//返回第一个元素
T &front()
{
return *first;
}
//返回最后一个元素
T &back()
{
return *(last-1);
}
//返回容器大小
int size()
{
return (last-first);
}
//清空容器
void clear()
{
last=first;
}
//二倍扩容
void expand()
{
int length = size();
int newvector = length*2; //扩容
T *newfirst = new T[newvector]; //创建新的连续空间
T *newlast = newfirst + length;
T *newend = newfirst + newvector;
for(int i=0;i<length;i++) //循环赋值
{
newfirst[i] = first[i];
}
delete []first; //释放之前的空间
first = newfirst; //改变指针
last = newlast;
end = newend;
}
//尾插
void push_back(const T &key)
{
if(full())
{
expand();
cout<<"已经二倍扩容,可以插入"<<endl;
}
*last = key;
last++;
if(last>end)
{
end = last;
}
}
//尾删
void pop_back()
{
if(empty())
{
cout<<"删除失败"<<endl;
return;
}
last--;
cout<<"删除成功"<<endl;
}
};
int main()
{
myvector<int> vec;
//插入
vec.push_back(1);
vec.push_back(4);
vec.push_back(9);
//输出
for(int i=0;i<vec.size();i++)
{
cout<<vec.at(i)<<" ";
}
cout<<endl;
//删除
vec.pop_back();
for(int i=0;i<vec.size();i++)
{
cout<<vec.at(i)<<" ";
}
cout<<endl;
return 0;
}
思维导图: