How does c++ std::vector work?

前端 未结 5 1178
北海茫月
北海茫月 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:35

    In terms of sizing, there are two values of interest for a std::vector: size, and capacity (accessed via .size() and .capacity()).

    .size() is the number of elements that are contained in the vector, whereas .capacity() is the number of elements that can be added to the vector, before memory will be re-allocated.

    If you .push_back() an element, size will increase by one, up until you hit the capacity. Once the capacity is reached, most (all?) implementations, re-allocate memory, doubling the capacity.

    You can reserve a capacity using .reserve(). For example:

    std::vector A;
    A.reserve(1);        // A: size:0, capacity:1  {[],x}
    A.push_back(0);      // A: size:1, capacity:1  {[0]}
    A.push_back(1);      // A: size:2, capacity:2  {[0,1]}
    A.push_back(2);      // A: size:3, capacity:4  {[0,1,2],x}
    A.push_back(3);      // A: size:4, capacity:4  {[0,1,2,3]}
    A.push_back(4);      // A: size:5, capacity:8  {[0,1,2,3,4],x,x,x}
    

    Reallocations of memory would occur at lines 4, 5, and 7.

提交回复
热议问题