vector memory allocation strategy

后端 未结 3 1330
慢半拍i
慢半拍i 2020-12-03 22:08

i wrote a little piece of code to determine, how memory allocating in a vector is done.

#include 
#inc         


        
相关标签:
3条回答
  • 2020-12-03 22:18

    How the vector is growing is implementation defined. So different strategies can be used resulting in different capacity after inserting the same count of elements

    If you need to rely on how many items are allocated you should use reserve and/or resize methods of vector

    0 讨论(0)
  • 2020-12-03 22:21

    As you can see, VS is adding extra space with smaller chunks, while G++ i doing it by the powers of 2. This is just implementations of the same basic idea: the more elements you add, the more space will be allocated next time (because it is more likely that you will add additional data).

    Imagine you've added 1 element to the vector, and I've added 1000. It's more likely that will add another 1000 and it is less likely that you will. This is the reasoning for such a strategy of allocating space.

    The exact numbers sure depends on something, but that's the reasoning of the compiler makers, since they can implement it in any way they want.

    0 讨论(0)
  • 2020-12-03 22:33

    The standard only defines a vector's behaviour. What really happens internally depends on the implementation. Doubling the capacity results in an amortized O(n) cost for pushing/popping n elements, which is required for a vector, I guess. Look here for more details.

    0 讨论(0)
提交回复
热议问题