Why no push/pop in front of vector?

后端 未结 4 764
灰色年华
灰色年华 2020-12-21 08:10

In C++, STL, we have template class . We know that it supports O(1) random access, and tail modification. My question is why we don\'

4条回答
  •  春和景丽
    2020-12-21 08:50

    One explanation is that if we want to push/pop element in the front of a vector, we must shift each element in the array by one step and that would cost O(n)

    You are absolutely right, push_front has no way to run quickly, because, in addition to a possible reallocation, all items need to be copied by one position. This gives you an amortized performance of O(n2) for n objects, which is not something that library designers wanted to encourage.

    Considering that if we implement with circular array

    Implementing vector with circular array makes it a lot harder to implement several important guarantees that must be true for a vector. For example, vector must guarantee that if iterator a points to an element with a lower index than iterator b, then a < b. When vector is linear, the comparison boils down to comparing addresses of elements to which iterators a and b are pointing. With a circular array implementation one would need to take the address of the vector origin into consideration, which can now be in the middle of the allocated block of memory.

    Another guaranteed that would be violated is this:

    When v is a vector, T is any type other than bool, and n a number between zero and vector's size, &v[n] == &v[0] + n identity must be true.

    This cannot be implemented with a circular array.

提交回复
热议问题