C++vector 简单实现

news/2025/2/13 0:53:54/

一。概述

vector是我们经常用的一个容器,其本质是一个线性数组。通过对动态内存的管理,增删改查数据,达到方便使用的目的。
作为一个线性表,控制元素个数,容量,开始位置的指针分别是

start  /*是数组的首地址*/
finish /*是数组元素的终止位置,看下图*/
end_of_storage/*是数组元素的总容量,看下图*/

大概的样子:
在这里插入图片描述
我们通过操作此三个指针和内存的增加减少或者复制转移的方式完成vector的成员方法。
下面是类成员定义的展示:

template<class _Ty> #类模板中没 有内存分配器,我们在函数中自己malloc实现#
class MyVector
{
public:typedef _Ty				value_type;typedef _Ty* pointer;typedef const _Ty* const_pointer;typedef _Ty& reference;typedef const _Ty& const_reference;typedef pointer        iterator;typedef const_pointer  const_iterator;typedef unsigned  int  size_type;
private:_Ty* _M_start;_Ty* _M_finish;_Ty* _M_end_of_storage;public:MyVector() :_M_start(nullptr), _M_finish(nullptr), _M_end_of_storage(nullptr) {}~MyVector() {clear();free(_M_start);}reference at(size_type pos){assert(pos >= 0 && pos < size());//return (*(pos + _M_start));return (_M_start[pos]);}const_reference at(size_type pos) const{assert(pos >= 0 && pos < size());return (*(pos + _M_start));}reference operator[](size_type pos){if (pos >= 0 && pos < size()) {return _M_start[pos];}else {std::cout << "error operator[]";exit(1);}}const_reference operator[](size_type pos) const{if (pos >= 0 && pos < size()) {return _M_start[pos];}else {std::cout << "error operator[]";exit(1);}}reference front(){return *_M_start;}const_reference front() const{return *_M_start;}reference back(){return *(_M_finish -1);}const_reference back() const{return *(_M_finish - 1);}_Ty* data(){return begin(); }const _Ty* data() const{return begin();}public:// 容量size_t size() const{return (size_t)(_M_finish - _M_start);}size_t capacity() const{return (size_t)(_M_end_of_storage - _M_start);}/*2/14*/bool empty()const{return size() > 0 ? true : false;}

二。重点成员方法解析

1.push_back尾部添加元素
不管pushback进的值是内置类型还是类类型,都应该是先创建一个空间,在此基础上生成对象实例化。实例化是在构造函数中进行的。
我们也要知道的是,一个进程的地址空间是4G,给定的数据(只读或是读、写数据)是固定大小,一旦容器像临时数组arr[100]的定义,那么的成员所占的内存如果过大或是动态的增减的难度,那么势必会不方便容器的使用,也不方便管理,所以使用动态内存来进行管理。

void push_back(const _Ty& val){if (_M_finish != _M_end_of_storage){new(_M_finish)_Ty(val);++_M_finish;}else {_M_insert_aux(end(),val);}}

_M_insert_aux 函数实现

_M_insert_aux函数中有一部分是从源空间的元素复制到新位置,此时挨个遍历,原位构造的方式相比于连续空间的赋值构造,我猜测后者效率更高一些(从cpuj计算的角度)。

		void _M_insert_aux(iterator pos, const _Ty& val) //{//const size_t oldsize = size();const size_t len = size() != 0 ? (size() * 1.5 + 1) : 1;//iterator new_start = (_Ty*)malloc(sizeof(_Ty) * len);iterator  start2 = (_Ty*)malloc(sizeof(_Ty) * len);//eg1:开始复制数据到新内存iterator newstart = start2;iterator newfinsh = _M_start;/*while (newfinsh != pos){new(newstart)_Ty(*newfinsh);++newstart;++newfinsh;}*//*new(newstart)_Ty(val);++newstart;*///eg1的另一种写法,测试:while (newfinsh != pos){memcpy(start2, _M_start, sizeof(_Ty)*(_M_finish-_M_start));newstart = _M_finish - _M_start + start2;newfinsh = _M_finish;}new(newstart)_Ty(val);++newstart;iterator it = _M_finish;while (newfinsh != _M_end_of_storage){++newfinsh;++newstart;}for (iterator it = _M_start; it != _M_finish; it++){it->~_Ty();}free(_M_start);_M_finish = newstart;_M_end_of_storage = len + start2;_M_start = start2;}

**2.operator =移动赋值
次函数需要注意的是什么形式时编译器调用的是赋值重载,什么形式时会调用拷贝构造。
隐式的拷贝构造:在创建对象性时的赋值,比如;
MyVector<Int
> tmp= arr;
显示的拷贝构造则是:
MyVector<Int
> tmp(arr);
如果你使用vector时的写法是隐式的,那么会调用拷贝构造完成对像的复制;
相反你使用显示的方式创建对象,也是会调用拷贝构造。
当你在创建对象后的赋值运算符的重载时才会调用vector的移动赋值函数

MyVector& operator= (const MyVector& V1)//在赋值运算符重载中不能在调用拷贝构造//因为this已经是一个对象,再拷贝构造创建一个对象,//是没什么意义的事情。{//arr.operator(V1);if (V1._M_start == nullptr&&_M_start ==nullptr) {return *this;}else if (this->_M_start == nullptr) { //拷贝构造/*iterator start = (_Ty*)malloc(sizeof(_Ty) * V1.capacity());_M_start = start;*/const_iterator it = V1.begin();while (it != V1._M_finish) {this->push_back(*it);++it;}/*_M_finish = ( _Ty* )it;_M_end_of_storage = V1.capacity()+_M_start;*/return *this;}else if (this->_M_start != nullptr) {if (this->size() >= V1.size()){/*for (iterator it = _M_start; it != _M_finish; ++it){it->~_Ty();}*/this->clear();iterator it = (_Ty*)V1.begin();while (it != V1._M_finish) {this->push_back(*it);++it;}return *this;}else {this->clear();free(_M_start);_M_start = nullptr;_M_finish = nullptr;this->_M_end_of_storage = nullptr;/*	iterator start = (_Ty*)malloc(sizeof(_Ty) * V1.capacity());_M_start = start;*/iterator it = (_Ty*)V1.begin();//iterator it =V1._M_start;while (it != V1._M_finish) {this->push_back(*it);++it;}/*_M_finish = it;_M_end_of_storage = V1.capacity() + _M_start;*/return *this;}}}

3.拷贝构造
注意:在类的成员方法内部不要在类中几个默认的成员函数(构造,析构,赋值重载,取地址运算符的重载)中调用拷贝构造,没有什么意义。从面向对象编程的角度讲不符合现实世界的逻辑。

MyVector(const MyVector& V1){cout << this << endl;iterator start = (_Ty*)malloc(sizeof(_Ty) * V1.capacity());if (start == nullptr){std::cout << "malloc error" << std::endl;exit(1);}iterator finish = start;iterator p = V1._M_start;_M_start = start;while (p != V1._M_finish){new(finish)_Ty(*p);++p;++finish;}_M_finish = finish;_M_end_of_storage = _M_start + V1.capacity();}

4.erase

iterator erase(iterator _F, iterator _L){if (_F != _L){if (_L != _M_finish) copy(_L, _M_finish, _F);_M_finish = _M_finish - (_L - _F);memset(_M_finish , 0x00, sizeof(_Ty) * (_L - _F));}return _L;}iterator erase(iterator pos)//有返回值,迭代器返回{return erase(pos, pos + 1);/*if (pos != end()) //这个代码可被erase(pos,pos+1)替代{copy(pos+1,_M_finish,pos);(--_M_finish)->~_Ty();}return pos;*/}

需要注意的是,上面使用到memcpy/memmove/copy函数时,不能保证对有虚函数的类(能产生多态的类)可以继续使用多态。原因是虚函数表和虚表指针丢失,无法找到函数指针(虚表指针应该不丢失)。


http://www.ppmy.cn/news/30694.html

相关文章

机器学习-卷积神经网络CNN中的单通道和多通道图片差异

背景 最近在使用CNN的场景中&#xff0c;既有单通道的图片输入需求&#xff0c;也有多通道的图片输入需求&#xff0c;因此又整理回顾了一下单通道或者多通道卷积的差别&#xff0c;这里记录一下探索过程。 结论 直接给出结论&#xff0c;单通道图片和多通道图片在经历了第一…

数据结构——链表OJ题目讲解(1)

作者&#xff1a;几冬雪来 时间&#xff1a;2023年3月7日 内容&#xff1a;数据结构链表OJ题目讲解 题目来源&#xff1a;力扣和牛客 目录 前言&#xff1a; 刷题&#xff1a; 1.移出链表元素&#xff1a; 2.链表的中间结点&#xff1a; 3. 链表中倒数第k个结点&#xff1…

Java方法的使用

目录 一、方法的概念及使用 1、什么是方法(method) 2、方法定义 3、方法调用的执行过程 4、实参和形参的关系 二、方法重载 1、为什么需要方法重载 2、方法重载概念 3、方法签名 三、递归 1、递归的概念 2、递归执行过程分析 一、方法的概念及使用 1、什么是方法(met…

k8s学习之路 | k8s 工作负载 ReplicaSet

文章目录1. ReplicaSet 基础概念1.1 RS 是什么&#xff1f;1.2 RS 工作原理1.3 什么时候使用 RS1.4 RS 示例1.5 非模板 Pod 的获得1.6 编写 RS1.7 使用 RS1.8 RS 替代方案2. ReplicaSet 与 ReplicationController2.1 关于 RS、RC2.2 两者的选择器区别2.3 总结1. ReplicaSet 基础…

recyclerview 使用的坑

1.有不同的布局 12_GridLayoutManager setSpanSizeLookup()方法 - 简书 setSpanSizeLookup 这个方法要会 spanCount和 getSpanSize spanCount/getSpanSize() 才是这一项所占的宽度 2.均分 item布局要设置宽度为match_paraent 3.设置完了。发现高度不一样&#xff0c;…

Linux 安装npm yarn pnpm 命令

下载安装包 node 下载地址解压压缩包 tar -Jxf node-v19.7.0-linux-x64.tar.xz -C /root/app echo "export PATH$PATH:/app/node-v16.9.0-linux-x64" >> /etc/profile source /etc/profile ln -sf /app/node-v16.9.0-linux-x64/bin/npm /usr/local/bin/ ln -…

Lab2_Simple Shell_2020

Lab2: 实验目的&#xff1a;给xv6添加新的系统调用 并理解系统调用是如何工作的&#xff0c;并理解xv6内核的一些内部特征 实验准备&#xff1a; 阅读xv6的第2章以及第4章的4.3,4.3小节熟悉下面的源码 用户态相关的代码&#xff1a;user/user.h和user/usys.pl内核态相关的代…

【极致简洁】Python tkinter 实现下载工具,你想要的一键获取

嗨害大家好鸭&#xff01;我是小熊猫~开发环境本次项目案例步骤成品效果【咱追求的就是一个简洁】界面如何开始&#xff1f;1.导入模块2.创建窗口【这步很重要】功能按键1.创建一个下拉列表2.设置下拉列表的值3.设置其在界面中出现的位置 column代表列 row 代表行4.设置下拉列表…