How is dynamic memory managed in std::vector?

后端 未结 4 1510
南笙
南笙 2021-01-03 08:52

How does std::vector implement the management of the changing number of elements: Does it use realloc() function, or does it use a linked list?

Thanks.

4条回答
  •  借酒劲吻你
    2021-01-03 09:31

    std::vector stored data in contiguous memory blocks.

    Suppose we declare a vector as

    std::vector intvect;

    So initially a memory of x elements will be created . Here x is implementation depended.

    If user is inserting more than x elements than a new memory block will be created of 2x (twice the size)elements and initial vector is copied into this memory block.

    Thats why it is always recommended to reserve memory for vector by calling reserve function.

    intvect.reserve(100);

    so as to avoid deletion and copying of vector data.

提交回复
热议问题