STL vector容器自己实现

2024-06-22 22:18
文章标签 stl vector 容器 实现

本文主要是介绍STL vector容器自己实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文参考了侯捷的 《STL 源码分析》一书,出于兴趣,自行实现了简单的 vector 容器。

之后会陆续上传 list, deque 等容器的代码,若有错误,欢迎留言指出。


vector 容易实现的几点注意事项:

1. 由于vector 是动态数组。

出于效率的考虑,在往vector 中加入元素时,内存的扩展遵循的规则是:

   1> 如果当前可用内存不够,开 2倍大的内存,将原来的数组复制到新数组中,撤销原来的数组。

   2> 加入新的元素

2. 通常当我们 int *p = new int(1)时, new 其实做了两件事情: 1> 分配内存   2>在分配的内存中调用类的构造函数。

出于效率的考虑,在 vector 的内存管理中,我们将这两个操作分开。

C++ 提供了 模板类 allocator 来实现上述的功能。

3. vector 中三个指针,分别是 start, finish, end_of_storage;

    [start, finish) 就是数组元素;

    [finish, end_of_storage) 是预先分配的空间(还没有调用构造函数)


参考书籍:

1. C++ primer, Lippman

2. STL 源码分析, 侯捷


[cpp] view plain copy
print ?
  1. // Last Update:2014-04-11 15:44:44  
  2. /** 
  3.  * @file vector.h 
  4.  * @brief a simple vector class 
  5.  * @author shoulinjun@126.com 
  6.  * @version 0.1.00 
  7.  * @date 2014-04-09 
  8.  */  
  9.   
  10. #ifndef MY_VECTOR_H  
  11. #define MY_VECTOR_H  
  12.   
  13. #include <iostream>  
  14. #include <algorithm>  
  15. #include <memory>  
  16.   
  17.   
  18. template<class T>  
  19. void destroy(T* pointer)  
  20. {  
  21.   pointer->~T();  
  22. }  
  23.   
  24. template<class ForwardIterator>  
  25. void destroy(ForwardIterator first, ForwardIterator last)  
  26. {  
  27.   for(ForwardIterator it = first; it != last; ++ it)  
  28.   {  
  29.     destroy(&*it);  
  30.   }  
  31. }  
  32.   
  33. template<class T>  
  34. class MyVector  
  35. {  
  36. public:  
  37.   typedef T  value_type;  
  38.   typedef T* iterator;  
  39.   typedef const T*const_iterator;  
  40.   typedef T* pointer;  
  41.   typedef const T* const_pointer;  
  42.   typedef T& reference;  
  43.   typedef const T& const_reference;  
  44.   typedef size_t size_type;  
  45.   
  46.   MyVector();  
  47.   MyVector(size_type n, T value = T());  
  48.   MyVector(iterator begin, iterator end);  
  49.   ~MyVector();  
  50.   
  51.   //copy control  
  52.   MyVector(const MyVector&);  
  53.   MyVector& operator=(const MyVector&);  
  54.   
  55.   bool empty() const { return begin() == end(); }  
  56.   size_type size() const {return (size_type)(finish - start);}  
  57.   size_type capacity() const {return (size_type)(end_of_storage - start);}  
  58.   
  59.   iterator begin() { return start; }  
  60.   const_iterator begin() constreturn start; }  
  61.   iterator end()   { return finish;}  
  62.   const_iterator end() constreturn finish; }  
  63.   
  64.   reference operator[](size_type i){return *(start + i);}  
  65.   const_reference operator[](size_type i)const {return *(start + i);}  
  66.   
  67.   void insert(iterator position, size_type n, const T& value);  
  68.   void push_back(const T& value);  
  69.   void pop_back();  
  70.   
  71.   void erase(iterator first, iterator last);  
  72.   void clear();  
  73.   
  74.   void reserve(size_type n);  
  75. protected:  
  76.   iterator start;   //空间的头  
  77.   iterator finish;  //空间的尾  
  78.   iterator end_of_storage; //可用空间的尾巴  
  79. private:  
  80.   static std::allocator<T> alloc; // object to get raw memory  
  81. };  
  82.   
  83. // static class member needed to be defined outside of class  
  84. template<class T>  
  85. std::allocator<T> MyVector<T>::alloc;  
  86.   
  87. // default constructor  
  88. template<class T>  
  89. MyVector<T>::MyVector()  
  90.   : start(NULL), finish(NULL), end_of_storage(NULL)  
  91. {  
  92. }  
  93.   
  94. template<class T>  
  95. MyVector<T>::MyVector(size_type n, T value)  
  96. {  
  97.   start = alloc.allocate(n);  
  98.   end_of_storage = finish = start + n;  
  99.   
  100.   for(iterator i=start; i!=finish; ++i)  
  101.     alloc.construct(i, value);  
  102. }  
  103.   
  104. template<class T>  
  105. MyVector<T>::MyVector(iterator begin, iterator end)  
  106. {  
  107.   const size_type n = end - begin;  
  108.   /* allocate space */  
  109.   start = alloc.allocate(n);  
  110.   finish = end_of_storage = start + n;  
  111.   
  112.   /* call constructor */  
  113.   std::uninitialized_copy(begin, end, start);  
  114. }  
  115.   
  116. template<class T>  
  117. MyVector<T>::~MyVector()  
  118. {  
  119.   /* call destructor */  
  120.   ::destroy(start, finish);  
  121.   
  122.   /* free space */  
  123.   alloc.deallocate(start, end_of_storage - start);  
  124. }  
  125.   
  126. // copy control  
  127. template<class T>  
  128. MyVector<T>::MyVector(const MyVector& rhs)  
  129. {  
  130.   start = alloc.allocate(rhs.capacity());  
  131.   std::uninitialized_copy(rhs.start, rhs.finish, start);  
  132.   finish = start + (rhs.finish - rhs.start);  
  133.   end_of_storage = start + (rhs.end_of_storage - rhs.start);  
  134. }  
  135.   
  136. template<class T>  
  137. MyVector<T>& MyVector<T>::operator=(const MyVector& rhs)  
  138. {  
  139.   start = alloc.allocate(rhs.capacity());  
  140.   std::uninitialized_copy(rhs.start, rhs.finish, start);  
  141.   finish = start + rhs.finish - rhs.start;  
  142.   end_of_storage = start + rhs.end_of_storage - rhs.start;  
  143.   
  144.   return *this;  
  145. }  
  146.   
  147. template<class T>  
  148. void MyVector<T>::insert(iterator position, size_type n, const T& value)  
  149. {  
  150.   if(n <= end_of_storage - finish)  
  151.   {/* enough memory */   
  152.     if(n <= finish - position)  
  153.     {  
  154.       std::uninitialized_copy(finish-n, finish, finish);  
  155.       std::copy(position, finish-n, position+n);  
  156.       std::fill_n(position, n, value);  
  157.     }  
  158.     else  
  159.     {   
  160.       std::uninitialized_fill_n(finish, n - (finish - position), value);  
  161.       std::uninitialized_copy(position, finish, position + n);  
  162.       std::fill(position, finish, value);  
  163.     }  
  164.     finish += n;  
  165.   }  
  166.   else  
  167.   {/* reallocate */  
  168.     pointer new_start(NULL), new_finish(NULL);  
  169.     size_type old_type = end_of_storage - start;   
  170.     size_type new_size = old_type + std::max(old_type, n);  
  171.     new_start = alloc.allocate(new_size);  
  172.   
  173.     // copy old vector to new vector  
  174.     new_finish = std::uninitialized_copy(start, position, new_start);  
  175.     std::uninitialized_fill_n(new_finish, n, value);  
  176.     new_finish += n;  
  177.     new_finish = std::uninitialized_copy(position, finish, new_finish);  
  178.   
  179.     alloc.deallocate(start, end_of_storage - start);  
  180.   
  181.     start = new_start;  
  182.     finish = new_finish;  
  183.     end_of_storage = new_start + new_size;  
  184.   }  
  185. }  
  186.   
  187. template<class T>  
  188. void MyVector<T>::push_back(const T &value)  
  189. {  
  190.   insert(end(), 1, value);  
  191. }  
  192.   
  193. template<class T>  
  194. void MyVector<T>::pop_back()  
  195. {  
  196.   alloc.destroy(--finish);  
  197. }  
  198.   
  199. template<class T>  
  200. void MyVector<T>::erase(iterator first, iterator last)  
  201. {   
  202.   iterator old_finish = finish;  
  203.   finish = std::copy(last, finish, first);  
  204.   ::destroy(finish, old_finish);  
  205. }  
  206.   
  207. template<class T>  
  208. void MyVector<T>::clear()  
  209. {  
  210.   erase(start, finish);  
  211. }  
  212.   
  213. template<class T>  
  214. void MyVector<T>::reserve(size_type n)  
  215. {  
  216.   if(capacity() < n)  
  217.   {  
  218.     iterator new_start = alloc.allocate(n);  
  219.     std::uninitialized_copy(start, finish, new_start);  
  220.   
  221.     ::destroy(start, finish);  
  222.     alloc.deallocate(start, size());  
  223.   
  224.     const size_type old_size = finish - start;  
  225.     start = new_start;  
  226.     finish = new_start + old_size;  
  227.     end_of_storage = new_start + n;  
  228.   }  
  229. }  
  230.   
  231.   
  232.   
  233.   
  234. #endif  /*MY_VECTOR_H*/  
// Last Update:2014-04-11 15:44:44
/*** @file vector.h* @brief a simple vector class* @author shoulinjun@126.com* @version 0.1.00* @date 2014-04-09*/#ifndef MY_VECTOR_H
#define MY_VECTOR_H#include <iostream>
#include <algorithm>
#include <memory>template<class T>
void destroy(T* pointer)
{pointer->~T();
}template<class ForwardIterator>
void destroy(ForwardIterator first, ForwardIterator last)
{for(ForwardIterator it = first; it != last; ++ it){destroy(&*it);}
}template<class T>
class MyVector
{
public:typedef T  value_type;typedef T* iterator;typedef const T*const_iterator;typedef T* pointer;typedef const T* const_pointer;typedef T& reference;typedef const T& const_reference;typedef size_t size_type;MyVector();MyVector(size_type n, T value = T());MyVector(iterator begin, iterator end);~MyVector();//copy controlMyVector(const MyVector&);MyVector& operator=(const MyVector&);bool empty() const { return begin() == end(); }size_type size() const {return (size_type)(finish - start);}size_type capacity() const {return (size_type)(end_of_storage - start);}iterator begin() { return start; }const_iterator begin() const{ return start; }iterator end()   { return finish;}const_iterator end() const{ return finish; }reference operator[](size_type i){return *(start + i);}const_reference operator[](size_type i)const {return *(start + i);}void insert(iterator position, size_type n, const T& value);void push_back(const T& value);void pop_back();void erase(iterator first, iterator last);void clear();void reserve(size_type n);
protected:iterator start;   //空间的头iterator finish;  //空间的尾iterator end_of_storage; //可用空间的尾巴
private:static std::allocator<T> alloc; // object to get raw memory
};// static class member needed to be defined outside of class
template<class T>
std::allocator<T> MyVector<T>::alloc;// default constructor
template<class T>
MyVector<T>::MyVector(): start(NULL), finish(NULL), end_of_storage(NULL)
{
}template<class T>
MyVector<T>::MyVector(size_type n, T value)
{start = alloc.allocate(n);end_of_storage = finish = start + n;for(iterator i=start; i!=finish; ++i)alloc.construct(i, value);
}template<class T>
MyVector<T>::MyVector(iterator begin, iterator end)
{const size_type n = end - begin;/* allocate space */start = alloc.allocate(n);finish = end_of_storage = start + n;/* call constructor */std::uninitialized_copy(begin, end, start);
}template<class T>
MyVector<T>::~MyVector()
{/* call destructor */::destroy(start, finish);/* free space */alloc.deallocate(start, end_of_storage - start);
}// copy control
template<class T>
MyVector<T>::MyVector(const MyVector& rhs)
{start = alloc.allocate(rhs.capacity());std::uninitialized_copy(rhs.start, rhs.finish, start);finish = start + (rhs.finish - rhs.start);end_of_storage = start + (rhs.end_of_storage - rhs.start);
}template<class T>
MyVector<T>& MyVector<T>::operator=(const MyVector& rhs)
{start = alloc.allocate(rhs.capacity());std::uninitialized_copy(rhs.start, rhs.finish, start);finish = start + rhs.finish - rhs.start;end_of_storage = start + rhs.end_of_storage - rhs.start;return *this;
}template<class T>
void MyVector<T>::insert(iterator position, size_type n, const T& value)
{if(n <= end_of_storage - finish){/* enough memory */ if(n <= finish - position){std::uninitialized_copy(finish-n, finish, finish);std::copy(position, finish-n, position+n);std::fill_n(position, n, value);}else{ std::uninitialized_fill_n(finish, n - (finish - position), value);std::uninitialized_copy(position, finish, position + n);std::fill(position, finish, value);}finish += n;}else{/* reallocate */pointer new_start(NULL), new_finish(NULL);size_type old_type = end_of_storage - start; size_type new_size = old_type + std::max(old_type, n);new_start = alloc.allocate(new_size);// copy old vector to new vectornew_finish = std::uninitialized_copy(start, position, new_start);std::uninitialized_fill_n(new_finish, n, value);new_finish += n;new_finish = std::uninitialized_copy(position, finish, new_finish);alloc.deallocate(start, end_of_storage - start);start = new_start;finish = new_finish;end_of_storage = new_start + new_size;}
}template<class T>
void MyVector<T>::push_back(const T &value)
{insert(end(), 1, value);
}template<class T>
void MyVector<T>::pop_back()
{alloc.destroy(--finish);
}template<class T>
void MyVector<T>::erase(iterator first, iterator last)
{ iterator old_finish = finish;finish = std::copy(last, finish, first);::destroy(finish, old_finish);
}template<class T>
void MyVector<T>::clear()
{erase(start, finish);
}template<class T>
void MyVector<T>::reserve(size_type n)
{if(capacity() < n){iterator new_start = alloc.allocate(n);std::uninitialized_copy(start, finish, new_start);::destroy(start, finish);alloc.deallocate(start, size());const size_type old_size = finish - start;start = new_start;finish = new_start + old_size;end_of_storage = new_start + n;}
}#endif  /*MY_VECTOR_H*/


这篇关于STL vector容器自己实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1085566

相关文章

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

LeetCode11. 盛最多水的容器题解

LeetCode11. 盛最多水的容器题解 题目链接: https://leetcode.cn/problems/container-with-most-water 示例 思路 暴力解法 定住一个柱子不动,然后用其他柱子与其围住面积,取最大值。 代码如下: public int maxArea1(int[] height) {int n = height.length;int

通过SSH隧道实现通过远程服务器上外网

搭建隧道 autossh -M 0 -f -D 1080 -C -N user1@remotehost##验证隧道是否生效,查看1080端口是否启动netstat -tuln | grep 1080## 测试ssh 隧道是否生效curl -x socks5h://127.0.0.1:1080 -I http://www.github.com 将autossh 设置为服务,隧道开机启动

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测 目录 时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测基本介绍程序设计参考资料 基本介绍 MATLAB实现LSTM时间序列未来多步预测-递归预测。LSTM是一种含有LSTM区块(blocks)或其他的一种类神经网络,文献或其他资料中LSTM区块可能被描述成智能网络单元,因为

亮相WOT全球技术创新大会,揭秘火山引擎边缘容器技术在泛CDN场景的应用与实践

2024年6月21日-22日,51CTO“WOT全球技术创新大会2024”在北京举办。火山引擎边缘计算架构师李志明受邀参与,以“边缘容器技术在泛CDN场景的应用和实践”为主题,与多位行业资深专家,共同探讨泛CDN行业技术架构以及云原生与边缘计算的发展和展望。 火山引擎边缘计算架构师李志明表示:为更好地解决传统泛CDN类业务运行中的问题,火山引擎边缘容器团队参考行业做法,结合实践经验,打造火山

vue项目集成CanvasEditor实现Word在线编辑器

CanvasEditor实现Word在线编辑器 官网文档:https://hufe.club/canvas-editor-docs/guide/schema.html 源码地址:https://github.com/Hufe921/canvas-editor 前提声明: 由于CanvasEditor目前不支持vue、react 等框架开箱即用版,所以需要我们去Git下载源码,拿到其中两个主

android一键分享功能部分实现

为什么叫做部分实现呢,其实是我只实现一部分的分享。如新浪微博,那还有没去实现的是微信分享。还有一部分奇怪的问题:我QQ分享跟QQ空间的分享功能,我都没配置key那些都是原本集成就有的key也可以实现分享,谁清楚的麻烦详解下。 实现分享功能我们可以去www.mob.com这个网站集成。免费的,而且还有短信验证功能。等这分享研究完后就研究下短信验证功能。 开始实现步骤(新浪分享,以下是本人自己实现

基于Springboot + vue 的抗疫物质管理系统的设计与实现

目录 📚 前言 📑摘要 📑系统流程 📚 系统架构设计 📚 数据库设计 📚 系统功能的具体实现    💬 系统登录注册 系统登录 登录界面   用户添加  💬 抗疫列表展示模块     区域信息管理 添加物资详情 抗疫物资列表展示 抗疫物资申请 抗疫物资审核 ✒️ 源码实现 💖 源码获取 😁 联系方式 📚 前言 📑博客主页:

探索蓝牙协议的奥秘:用ESP32实现高质量蓝牙音频传输

蓝牙(Bluetooth)是一种短距离无线通信技术,广泛应用于各种电子设备之间的数据传输。自1994年由爱立信公司首次提出以来,蓝牙技术已经经历了多个版本的更新和改进。本文将详细介绍蓝牙协议,并通过一个具体的项目——使用ESP32实现蓝牙音频传输,来展示蓝牙协议的实际应用及其优点。 蓝牙协议概述 蓝牙协议栈 蓝牙协议栈是蓝牙技术的核心,定义了蓝牙设备之间如何进行通信。蓝牙协议

python实现最简单循环神经网络(RNNs)

Recurrent Neural Networks(RNNs) 的模型: 上图中红色部分是输入向量。文本、单词、数据都是输入,在网络里都以向量的形式进行表示。 绿色部分是隐藏向量。是加工处理过程。 蓝色部分是输出向量。 python代码表示如下: rnn = RNN()y = rnn.step(x) # x为输入向量,y为输出向量 RNNs神经网络由神经元组成, python