当前位置: 首页 > news >正文

c++day7

 仿照vector手动实现自己的myVector,最主要实现二倍扩容功能

#include <iostream>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<num;++i){start[i]=val;last++;}}//定义拷贝构造函数Myvector(const Myvector<T> *other){this->start=new T[other->end -other->first+1];this->last=other->last;this->end=other->end;for(int i=0;i<other->end-other->start;++i){this->first[i]=other->first[i];}}//定义拷贝赋值函数Myvector &operator=(const Myvector<T>*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<other->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<<"越界了"<<endl;}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<<"容器空了"<<endl;}last--;}//begin()返回第一个元素的迭代器T*begin()const{return start;}//end()T*pend(){return last;}};
int main()
{Myvector<int>m(2,5);cout<<m.at(1)<<endl;cout<<m.size()<<endl;//大小m.push_back(6);cout<<m.size()<<endl;//大小Myvector<int>n(m);n.pop_back();cout<<m.at(1)<<endl;return 0;
}

思维导图

http://www.lryc.cn/news/166354.html

相关文章:

  • C++学习概述
  • 关系型数据库和非关系型数据库
  • 基于SSM的快餐店点餐服务系统设计与实现
  • 使用vcpkg配置CGAL+visual studio 2022
  • 【Spring面试】三、Bean的配置、线程安全、自动装配
  • flink连接kafka报:org.apache.kafka.common.errors.TimeoutException
  • sql order by 排序 null值放最后,怎么写
  • HDMI字符显示实验
  • Spring Cloud 框架搭建
  • 20个非常有用的单行Python代码片段
  • 【LangChain系列 9】Prompt模版——MessagePromptTemplate
  • ROS2的学习路径
  • Maintaining leader role through timed lease mechanism
  • Mysql InnoDB引擎 的hash索引
  • 23年PMP考试如何备考?
  • mysql数据库增量备份方案、备份计划(InsCode AI 创作助手)
  • 【Flink】FlinkCDC获取mysql数据时间类型差8小时时区解决方案
  • Javas | DecimalFormat类、BigDecimal类、Random类
  • 机器学习 实战系列 总目录
  • 机器学习——贝叶斯(三种分布)/鸢尾花分类分界图/文本分类应用
  • SOLIDWORKS Composer位置关键帧的使用
  • PostgreSQL 流复制搭建与维护
  • 【Redis】关于过期数据清除的一些策略
  • 动态SQL
  • uniapp:OCR识别身份证上传原图失败,问题解决
  • shell循环和函数
  • 京东详情api
  • MySQL最新版8.1.0安装配置教程
  • 5G试题_1
  • 正规股票配资网站的三个明显特点分析