仿照vector手动实现自己的myVector,最主要实现二倍扩容功能
#include <iostream>
using namespace std;
class myvector
{
private:
int *num;
int size;
int top=0;
public:
//有参构造函数
myvector(int s,int val)
{
int *tmp=new int [s];
size=s;
for(int i=0;i<s;i++)
{
tmp[i]=val;
top++;
}
num=tmp;
}
//析构函数
~myvector()
{
delete [] num;
}
//展示函数
void show()
{
for(int i=0;i<top;i++)
{
cout<<num[i]<<" ";
}
cout<<endl;
}
//尾插
void push_back(int val)
{
if(top==size)
{
size=size*2;
int *tmp=new int[size];
memcpy(tmp,num,sizeof(int)*size/2);
num=tmp;
}
num[top]=val;
top++;
}
int at(int a)
{
if(a<top)
{
return num[a];
}else
{
return *num;
}
}
//插入
void inset(int s,int val)
{
if(top==size)
{
if(size==0)
{
size=2;
int *tmp=new int[size];
memcpy(tmp,num,sizeof(int)*size/2);
num=tmp;
}
size=size*2;
int *tmp=new int[size];
memcpy(tmp,num,sizeof(int)*size/2);
num=tmp;
}
for(int i=top;i>s;i--)
{
num[i]=num[i-1];
}
num[s]=val;
top++;
}
//删除
void dele(int s)
{
if(s<size)
{
for(int i=s;i<top-1;i++)
{
num[i]=num[i+1];
}
top--;
}
}
//改
void gai(int s,int val)
{
if(s<size)
{
num[s-1]=val;
}
}
int back()
{
return num[top];
}
int *begin()
{
return num;
}
int capacity()
{
return size;
}
void claer()
{
top=size=0;
delete []num;
num=nullptr;
}
int front()
{
return *num;
}
void pop_back()
{
top--;
}
int *end()
{
return num+top;
}
int ysdx()
{
return top;
}
void swap(int s,int n)
{
int tmp=num[s];
num[s]=num[n];
num[n]=tmp;
}
};
int main()
{
myvector a1(2,123);
a1.push_back(199);
a1.inset(3,1);
a1.dele(3);
a1.at(4);
a1.gai(3,100);
a1.show();
return 0;
}