思维导图
Vector
#include <iostream>
using namespace std;
template <typename V>
class Myvector{
private:
V *data;
int Capacity;
int Size;
public:
//无参构造
Myvector():data(new V[Capacity]),Capacity(0),Size(0){
cout<<"无参构造函数"<<endl;
}
//有参构造
Myvector(int c,int s):Capacity(c),Size(s){
data=new V[Capacity];
cout<<"有参构造函数"<<endl;
}
//析构函数
~Myvector(){
delete []data;
cout<<"析构函数"<<endl;
}
//拷贝构造函数
Myvector(const Myvector &other):data(new V[other.Capacity]),Capacity(other.Capacity),Size(other.Size){
for (int i = 0; i < Size; i++) {
data[i] = other.data[i];
}
cout<<"拷贝构造函数"<<endl;
}
//拷贝赋值函数
Myvector &operator= (const Myvector &other){
if(this!=&other){
this->Capacity=other.Capacity;
this->Size=other.Size;
}
if(this->data!=NULL){
delete this->data;
}
this->data=new V(*other.data);
for (int i = 0; i < Size; i++) {
data[i] = other.data[i];
}
cout<<"拷贝赋值函数"<<endl;
return *this;
}
//判空函数
bool empty(){
return 0==Size;
}
//capacity函数
int capacity(){
return Capacity;
}
//size函数
int size(){
return Size;
}
//插入函数
void insert(int pos,V e){
if(pos<0||pos>Size){
throw string("下标不能小于0,不能超过Size");
}
else{
if(Size==Capacity){
V* temp=new V[Capacity*2];
for (int i = 0; i < Size; i++) {
temp[i] = data[i];
}
delete this->data;
this->data=temp;
this->Capacity*=2;
}
for(int i=Size;i>pos;i--){
data[i]=data[i-1];
}
data[pos]=e;
Size++;
}
cout<<"插入成功"<<endl;
}
//show函数
void show(){
for(int i=0;i<Size;i++){
cout<<data[i]<<'\t';
}
cout<<endl;
}
};
int main()
{
Myvector<int> v(5,0);
cout<<"容量:"<<v.capacity()<<endl;
cout<<"元素数量:"<<v.size()<<endl;
v.insert(0,1);
v.insert(0,2);
v.insert(0,3);
v.insert(0,4);
v.insert(0,5);
v.show();
v.insert(0,6);
cout<<"容量:"<<v.capacity()<<endl;
cout<<"元素数量:"<<v.size()<<endl;
v.insert(0,7);
v.insert(0,8);
v.insert(0,9);
v.insert(0,10);
v.insert(0,11);
v.insert(0,12);
cout<<"容量:"<<v.capacity()<<endl;
cout<<"元素数量:"<<v.size()<<endl;
v.show();
return 0;
}