On vector

On vector

Preface

  • Vector is generally used as a dynamically growing array, which is quite different from array
  • Here is mainly a summary of adding elements and deleting elements of vector

vector iterator

  • The protected member of vector has 3 iterators
  • start-the head of the currently used space
  • finish-the end of the currently used space
  • end_of_storage-the end of the current available space
  • Vector uses 2 iterators start and finish to indicate the range that has been used, and end_of_storage to indicate the range of the entire space
  • Similar to the following figure:
    Insert picture description here

Add elements

  1. The spare space is greater than or equal to the number of new elements
    && The number of existing elements after the insertion point is greater than the number of new elements
	先调用uninitialized_copy将finish之前的长度等同于新增元素长度的那一段拷贝到finish之后
	finish迭代器后移
	将插入点之后的刚才没移完的元素通过copy_backward函数拷贝到旧的finish迭代器之前
	从插入点开始填充插入的元素
  1. The spare space is greater than or equal to the number of new elements
    && The number of existing elements after the insertion point is less than or equal to the number of new elements
	先调用uninitialized_fill_n将finish迭代器之后的n - elems_after全设置成要插入的元素, n为插入的元素个数, elems_after为插入点之后的元素的个数
	调整finish迭代器
	将插入点之后的元素复制到空余的位置
	调整finish迭代器
	填充插入的元素
  1. The spare space is less than the number of new elements
	先申请一块新的空间
	新的空间的大小为 max(old_size, 新增元素个数) + old_size
	将插入点之前的元素copy到新空间
	将插入的元素填充到新空间
	将插入点之后的元素copy到新空间
	释放原来的空间
	将3个迭代器指向新的空间

Delete element

  • Deleting elements is easier than inserting elements
  • Deleting elements is to remove this space, adjust the finish iterator, the end_of_storage iterator basically does not move, and move the element after the deletion point forward

Guess you like

Origin blog.csdn.net/weixin_43891775/article/details/112977635