How does c++ std::vector work?

前端 未结 5 1135
北海茫月
北海茫月 2021-01-03 23:30

How does adding and removing elements \"rescale\" the data? How is the size of the vector calculated (I believe it is kept track of)? Any other additional resources to le

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 23:40

    The vector usually has three pointers. If the vector has never been used they are all 0, or NULL.

    • One to the first element of the vector. (this is the begin() iterator)
    • One to last element of the vector + 1. (this is the end() iterator)
    • And one more to the last allocated but unused element + 1. (this minus begin() is the capacity)

    When an element is inserted, the vector allocates some storage and sets its pointers. It might allocate 1 element, or it might allocate 4 elements. Or 50.

    Then it inserts the element and increments the last element pointer.

    When you insert more elements than are allocated the vector has to get more memory. It goes out and gets some. If the memory location changes then it has to copy all the elements into the new space and free the old space.

    A common choice for resizing is to double the allocation every time it needs more memory.

提交回复
热议问题