仿照vector手动实现自己的myVector,最主要实现二倍扩容功能
#include <iostream>using namespace std;template <typename T>
class Myvector
{T *data; //存储数据的数组int len; //当前数组的长度int mycapa; //容纳数据的总容量public://构造函数Myvector():data(NULL),len(0),mycapa(0){cout<<"无参构造"<<endl;}Myvector(int n, T a){data =new T[n];len = n;mycapa = n;for(int i=0;i<n;i++){data[i]=a;}cout<<"有参构造"<<endl;}//判空bool my_empty(){if(0 == len){return 0;}return 1;}//判满bool my_full(){if(len == mycapa){return 0;}return 1;}//在末尾插入一个元素int mypop_back(T a){if(0 == mycapa){mycapa = 1;data = new int[1];}else if(len+1 > mycapa) //如果数组长度大于最大容量,最大容量二倍扩容{mycapa = 2*len;int *p = new int[mycapa];for(int i=0; i<len; i++){p[i] = data[i];}delete []data;data = p;}data[len] = a;len++;}//任意插入void my_insert(int pos, T a){if(0 == mycapa){mycapa = 1;data = new int[1];data[0] = a;}else if(len+1 > mycapa){mycapa = 2*len;int *p = new int[mycapa];for(int i=0; i<pos; i++){p[i] = data[i];}p[pos] = a;for(int i=pos; i<len; i++){p[i+1] = data[i];}delete []data;data = p;}else{for(int i=len-1; i>=pos; i--){data[i+1] = data[i];}data[pos] = a;}len++;}//移除最后一个元素void mypop_back(){len--;cout<<"移除最后一个元素成功"<<endl;}//删除指定位置元素void my_erase(int pos){if(my_empty() && pos>len){cout<<"删除失败"<<endl;}for(int i=pos; i<len; i++){this->data[i-1] = this->data[i];}len--;cout<<"删除指定位置元素成功"<<endl;}//展示void my_show(){cout<<"展示元素";for(int i=0; i<len; i++){cout<<data[i];cout<<" ";}cout<<endl;}//返回能容纳的最大容量void my_capacity(){cout<<"最大容量为"<<mycapa<<endl;}//返回指定位置元素void my_at(int pos){cout<<"第"<<pos<<"个元素是"<<data[pos]<<endl;}//清空所有元素int my_clear(){cout<<"已全部清空"<<endl;return len=0;}};using namespace std;int main()
{Myvector<int> m(4,6); //有参构造创建了4个元素,每个元素都是6m.my_show();m.mypop_back(7); //尾插m.mypop_back(8);m.my_show();m.my_capacity(); //返回最大容量,此时为8cout<<"***************************************"<<endl;m.my_insert(5,9); //任意位置插入元素m.my_show();cout<<"***************************************"<<endl;m.my_erase(5); //任意位置删除元素m.my_show();cout<<"***************************************"<<endl;m.mypop_back(); //移除最后一个元素m.my_show();cout<<"***************************************"<<endl;m.my_at(2);m.my_clear(); //清空m.my_show();return 0;
}