Блог пользователя 0xA28

Автор 0xA28, история, 8 лет назад, По-английски

As I managed to understand, When we are dealing with some dynamic data structure which has an average cost of O(1) Amortized Analysis in push and pop operations like vector in c++, the vector takes constant time per each push till it reaches to the Nth push (N = current size reserved), in the Nth push it takes linear time to allocate a new space typically with double the old size, and pretty the same done in pop operations.

Now assume that we have a vector of N current reserved space with N — 1 elements, every time we push a new element into the vector then pop it again, is this done in a linear time to change the allocated space ? it seems not, but why ?

  • Проголосовать: нравится
  • +12
  • Проголосовать: не нравится

»
8 лет назад, # |
  Проголосовать: нравится +22 Проголосовать: не нравится

It doubles when it becomes full, true.

But it doesn't contracts as soon as half of the elements are empty, it contracts when 1/4th of the allocated memory is being used. There is some calculations of amortized analysis, that is used to proof that its yet O(1) in both push and pop regardless of the example you gave above.

Let us, vector x(y), where x is the used array and y is the allocated memory. So for example 4(4), an element is inserted and memory is doubled, now 5(8). If now pop is called new state would be 4(8) but there will be no contraction. Again pop sometimes and it becomes 3(8)->2(8), and only then it contracts to 2(4).

I hope you understand :)

»
8 лет назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится

The C++ Standard doesn't specify anything about reallocation when you pop_back from a vector, but there is the guarantee that no iterators will be invalidated after a call to pop_back, which implies that reallocation cannot occur.

Thankfully, when you care about the extra space your vectors are using, there's a shrink_to_fit method.

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Actually, I care about both the space and time, if i used shrink_to_fit every pop operation i would kill the time performance of the program. I think the proper thing to do is to check every pop operation if the size == 1/4 of the capacity then shrink_to_fit