要求:
构造函数 析构函数 拷贝构造 拷贝赋值 at() empty() full() front() back() size() clear() expand() 二倍扩容函数 push_back() pop_back()
代码如下:
#include <iostream>
using namespace std;
template <typename T>
class Myvector
{
private:
T * first;
T * last;
T * end;
public:
//构造函数
Myvector(int size = 4)
{
first = new T [size];
last = first;
end = first+size;
}
//析构函数
~Myvector()
{
delete []first;
first = nullptr;
}
//拷贝构造
Myvector (const Myvector &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;
}
//扩容
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;
}
//返回指定位置的元素
T &at(int index)
{
int len = last - first;
if(index<0||index>len)
{
cout<<"超出了"<<endl;
}
return first[index];
}
//判空
bool empty()
{
return this->last == this->first;
}
//判满
bool full()
{
return this->last==this->end;
}
//返回第一个元素
T &front()
{
return first;
}
//返回最后一个元素
T &back()
{
return last-1;
}
//返回元素数量大小
T size()
{
return end-first;
}
//clear()
//在最后添加一个元素
void push_back(const T e)
{
if(this->full())
{
this->expand();
}
*last = e;
last++;
}
//移除最后一个元素
void pop_back()
{
if(this->empty())
{
return;
}
last--;
}
};
int main()
{
Myvector<int> m;
m.push_back(2);
m.push_back(3);
m.push_back(4);
m.push_back(5);
m.push_back(6);
for(int i=0;i<=4;i++)
{
cout<<m.at(i)<<" ";
}
cout<<endl;
cout<< m.size()<<endl;;
return 0;
}
结果如下图所示: