仿照vector手动实现自己的myVector,最主要实现二倍扩容功能
- #include
-
- using namespace std;
- template <typename T>
- class Myvector
- {
- private:
- T *start;//起始指针
- T *end;//数组末尾指针
- T *last;//数组有效长度的尾指针
- public:
- //定义无参构造
- Myvector(){
- start=new T[2];
- last=start;
- end=start+1;
- }
- //定义有参构造
- Myvector(int num,const T &val)
- {
- start=new T[num+1];
- last=start;
- end=start+num;
- for(int i=0;i
- {
- start[i]=val;
- last++;
- }
-
- }
- //定义拷贝构造函数
- Myvector(const Myvector
*other) - {
- this->start=new T[other->end -other->first+1];
- this->last=other->last;
- this->end=other->end;
- for(int i=0;i
end-other->start;++i) - {
- this->first[i]=other->first[i];
- }
- }
- //定义拷贝赋值函数
- Myvector &operator=(const Myvector
*other){ - if(this!=other)
- {
- delete []start;
- this->first=new T[other->end-other->start+1];
- this->last=other->last;
- this->end=other->end;
- for(int i=0;i
end-other->start;i++) - {
- this->start[i]=other->start[i];
- }
- }
- return *this;
- }
- //析构函数
- ~Myvector()
- {
- delete []start;
- start=nullptr;
- last=nullptr;
- end=nullptr;
- }
- //at()函数
- T &at(int pos){
- if(pos>end-start)
- {
- cout<<"越界了"<
- }
- return start[pos];
- }
- //判空
- bool empty(){
- if(last==start)
- {
- return 1;
- }else{return 0;}
- }
- //front()函数
- T &front(){
- return *start;
- }
- //back()函数
- T &back(){
- return *(end-1);
- }
- //size()函数
- int size()
- {
- return last-start;
- }
- //二倍扩容
- void erkr(){
- if(end-start==1||last==start)
- {
-
-
- int len=end-start;
- start=new T[len*2];
- }
- last+=(end-start)-1;
- return;
- }
- //push_back()
- void push_back(const T &val)
- {
- if(last==end)//容器满了
- {
- erkr();
- }
- *last=val;
- last++;
-
- }
- //pop_back()
- void pop_back()//容器是空的
- {
- if(empty())
- {
- cout<<"容器空了"<
- }
- last--;
- }
-
- //begin()返回第一个元素的迭代器
- T*begin()const{
- return start;
- }
- //end()
- T*pend(){
- return last;
- }
-
- };
- int main()
- {
- Myvector<int>m(2,5);
- cout<
at(1)< - cout<
size()<//大小 - m.push_back(6);
- cout<
size()<//大小 - Myvector<int>n(m);
- n.pop_back();
-
-
相关阅读:
MySQL8窗口函数应用
基于python的图像识别
vue3 如何国际化
使用 JMeter 和 Docker 进行服务存根
设计模式——命令模式
内网安全【2】——域防火墙/入站出站规则/不出网隧道上线/组策略对象同步
笛卡尔树—简介
跨域资源共享CORS详解及常见错误解决方案
护眼灯真的可以保护眼睛吗?2022买什么护眼灯不伤孩子眼睛
安卓ro.serialno产生的整个流程
-
原文地址:https://blog.csdn.net/HYL1234511/article/details/132890509