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

相关文章

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合