仿照vector,编写自己的myvector
- #include
-
- using namespace std;
-
- template<typename T>
- class myvector
- {
- public:
- T *first;
- T *last;
- T *end;
- public:
- //无参构造
- myvector()
- {
- first = new T[1];
- last = first;
- end=first+1;
- cout<<"无参构造"<
- }
-
- //有参构造
- myvector(int l,T d)
- {
- first=new T[l];
- last=first;
- end=first+l;
- for(int i=0;i
- {
- first[i]=d;
- last++;
- }
- cout<<"有参构造"<
- }
-
- //拷贝构造
- myvector(const myvector &other)
- {
- first=new T[other.end-other.first];
- last=first;
- end=first+(other.end-other.first);
- for(int i=0;i
- {
- first[i]=other.first[i];
- last+=1;
- }
- cout<<"拷贝构造"<
- }
-
- //析构函数
- ~myvector()
- {
- delete []first;
- first=nullptr;
- last=nullptr;
- end=nullptr;
- cout<<"析构函数"<
- }
-
-
- //at函数
- T &myat(int x)
- {
- return first[x];
- }
-
- //back函数
- T myback()
- {
- return *last;
- }
-
- //capacity函数
- int mycapacity()
- {
- return end-first;
- }
-
-
- //clear函数
- void myclear()
- {
- last=first;
- }
-
- //二倍扩容
- void mydouble()
- {
- int y=end-first;
- int x =last-first;
- T *p=new T[y*2];
- for(int i=0;i
- {
- p[i]=first[i];
- }
-
- delete []first;
- first=p;
- last=first+x;
- end=first+y*2;
- p=nullptr;
- }
-
- //insert函数
- void myinsert(int n,T e)
- {
- last=last+1;
- if(last+1>=end)
- {
- mydouble();
- }
-
- for(int i=(last-first)+1;i>0;i--)
- {
- first[i]=first[i-1];
- if(i==n-1)
- {
- first[i]=e;
- return ;
- }
- }
- }
-
- //empty函数
- bool myempty()
- {
- if(last==first)
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
-
- void show()
- {
- for(int i=0;i
- {
- cout<
" "; - }
- cout<
- }
-
- };
-
- int main()
- {
- myvector<int>ve1(5,4);
- myvector<int>ve2(ve1);
- int y;
- y=ve1.mycapacity();
- cout<
- ve1.myinsert(4,6);
- ve1.myinsert(3,5);
- int z;
- z=ve1.mycapacity();
- ve1.show();
- cout<
-
- return 0;
- }
-
相关阅读:
《c++ Primer Plus 第6版》读书笔记(4)
win10更新错误0x800f0922的解决方法
4-10构造器
Qt的简单应用:五子棋游戏( 含源码 )
高压放大器在mems传感器中的应用有哪些
guava缓存使用不当导致的FullGC
25.CyclicBarrire的功能和作用
【0116】PostgreSQL/MVCC
【Kingbase FlySync】命令模式:安装部署同步软件,实现KES到KES实现同步
java基于springboot+vue的旅游心得分享攻略系统 elementui
-
原文地址:https://blog.csdn.net/2201_75732711/article/details/132890679