Why no push/pop in front of vector?

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

    Actually, this is a realistic requirement. To my knowledge, nothing in the standard mandates that the vector cannot have a buffer before the elements (v.prefix_capacity()), just as after (v.capacity() - v.size()). This could guarantee the same runtime for v.push_front() and v.push_back(), while not having any cost for those who don't use it. Additionally, it could guarantee O(1) v.pop_front(), albeit by invalidating iterators. Fancy writing a proposal?

    In the meanwhile, you might create a template (devector?) in terms of vector, which:

    • has a field pre_capacity_ initialized to 0 and a getter pre_capacity()
    • implements pre_reserve(size_t i) which calls both:
      • reserve(capacity() - pre_capacity_ + i)
      • pre_capacity_ += i
    • implements operator[](size_t i) and delegates to v[i + pre_capacity()]
    • implements at(size_t i) and delegates to v.at(i + pre_capacity())
    • implements begin() and delegates to v.begin() + pre_capacity()
    • delegates all the rest of the methods to vector

    Or you can just track the number of elements you've pushed to / popped from front :).

提交回复
热议问题