Amortized analysis of std::vector insertion

前端 未结 3 948
野趣味
野趣味 2020-12-14 02:22

How do we do the analysis of insertion at the back (push_back) in a std::vector? It\'s amortized time is O(1) per insertion. In particular in a video in channel9 by Stephan

3条回答
  •  半阙折子戏
    2020-12-14 03:21

    Uhm, the analysis is really simple when you're familiar with number systems, such as our usual decimal one.

    For simplicity, then, assume that each time the current capacity is reached, a new 10x as large buffer is allocated.

    If the original buffer has size 1, then the first reallocation copies 1 element, the second (where now the buffer has size 10) copies 10 elements, and so on. So with five reallocations, say, you have 1+10+100+1000+10000 = 11111 element copies performed. Multiply that by 9, and you get 99999; now add 1 and you have 100000 = 10^5. Or in other words, doing that backwards, the number of element copies performed to support those 5 reallocations has been (10^5-1)/9.

    And the buffer size after 5 reallocations, 5 multiplications by 10, is 10^5. Which is roughly a factor of 9 larger than the number of element copy operations. Which means that the time spent on copying is roughly linear in the resulting buffer size.

    With base 2 instead of 10 you get (2^5-1)/1 = 2^5-1.

    And so on for other bases (or factors to increase buffer size by).

    Cheers & hth.

提交回复
热议问题