#include <iostream>
using namespace std;
template<typename T>
class MyVector
{
private:
T*first;
T*last;
T*end;
public:
//无参构造
MyVector(){cout<<"无参构造"<<endl;}
//有参构造
MyVector(T size):first(new T(size)) //定义一个容器
{
this->end=this->first+size;
this->last=this->first;
cout<<"有参构造"<<endl;
}
//析构函数
~MyVector(){
if(this->first!=this->end){
cout<<"析构函数"<<endl;
}
}
//拷贝构造
MyVector(const MyVector&other)
{
int size=other.end-other.first;
int len=other.last-other.first;
//空间进行拷贝
memcpy(this->first,other.first,len*sizeof(T));
//更新指针
this->last=len+this->first;
this->end=this->first+size;
cout<<"拷贝构造"<<endl;
}
//拷贝赋值
MyVector &operator=(const MyVector&other)
{
int size=other.end-other.first;
int len=other.last-other.first;
//空间进行拷贝
memcpy(this->first,other.first,len*sizeof(T));
//更新指针
this->last=len+this->first;
this->end=this->first+size;
//cout<<"frist="<<first<<endl;
cout<<"拷贝赋值"<<endl;
return *this;
}
T &at(int pos){
int size=this->end-this->first;
if(pos<0||pos>size){
cout<<"位置错误"<<endl;
}
cout<<"***fis=="<<*(first+pos)<<endl;
return first[pos];
}
bool empty()
{
if(this->first==this->last){
return true;
}
else{
return false;
}
}
//判断是否满
bool full()
{
if(this->end==this->last){
return true;
}
else{
return false;
}
}
//front()函数返回当前vector起始元素的引用
T &front()
{
return first[0];
}
//返回最末一个元素
T &back(){
return end[0];
}
//返回Vecor元素数量的大小
T &size(){
return this->last-this->first;
}
//clear 清空所有元素
void clear()
{
int size=this->last-this->first;
for(int i=0;i<size;i++){
first[i]=0;
}
}
//二倍扩容
void expand()
{
int size=this->last-this->first;
if(this->last>=this->end){
T *p=this->first;
this->first=new T [size*2];
memcpy(this->first,p,size*2);
this->end=this->first+2*size;
}
}
//在vector最后添加一个元素
void push_back(T p)
{
if(full()){
expand();
}
*(this->last)=p;
this->last++;
}
//移除最后一个元素
void pop_back()
{
this->last--;
}
//遍历数据
void show()
{
int size=this->last-this->first;
for(int i=0;i<size;i++){
at(i);
}
cout<<endl;
}
};
int main()
{
//调用有参构造
MyVector<int> s(5);
//调用拷贝构造
MyVector<int> s1(s);
//调用拷贝赋值 实例话对象时才会析构
MyVector<int> s2;
s2=s;
//添加元素
s2.push_back(555);
s2.push_back(666);
s2.push_back(777);
s2.show();
cout<<"开始元素="<<s2.front()<<endl;
return 0;
}
C++ 2023-4-2 作业
最新推荐文章于 2024-10-01 23:33:30 发布