STL vector容器自己实现

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

本文主要是介绍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

相关文章

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

通过Docker容器部署Python环境的全流程

《通过Docker容器部署Python环境的全流程》在现代化开发流程中,Docker因其轻量化、环境隔离和跨平台一致性的特性,已成为部署Python应用的标准工具,本文将详细演示如何通过Docker容... 目录引言一、docker与python的协同优势二、核心步骤详解三、进阶配置技巧四、生产环境最佳实践

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima