Why no push/pop in front of vector?

后端 未结 4 776
灰色年华
灰色年华 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:32

    Implementing a de-vector introduces 2 challenges:

    • Retaining O(1) random access (unlike: deque).
    • O(1) push operation, to either side (front or back), which's the benefit of deque.

    Both are achievable, in the following manner:

    • Implement a devector class, which publicly inherits from std::vector. Hence we have the std::vector API available, and "just" need to override the methods which require overriding.
    • The inherited vector (base class) will be utilized for regular push_back insertions.
    • The devector class will also have a private std::vector member, let's refer it as front_insertions.
    • Any push_front to the devector, will perform push_back to front_insertions (the private member vector).
    • Size of devector will be the sum of both sizes: the inherited vector, and the size of front_insertions.
    • Random access to an element of index i, will be implemented in the following manner: If front_insertions is empty, we just reuse the inherited random access method as-is. Else if i < front_insertions.size() we access front_insertions[front_insertions.size() - 1 - i]. Else, we access [i - front_insertions.size()] of the inherited vector.
    • Obviously, some other std::vector methods can be overriden, such as emplace_back, emplace_front, at, etc'. I focused on retaining both O(1) random access, and push to either side.

提交回复
热议问题