Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
814 views
in Technique[技术] by (71.8m points)

c++ - Why no push/pop in front of vector?

In C++, STL, we have template class <vector>. We know that it supports O(1) random access, and tail modification. My question is why we don't define push_front, or pop_front in <vector>?

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).

But I think that is not always the case. Considering that if we implement <vector> with circular array, we can achieve O(1) push/pop from both front and tail of the vector, without losing the ability of O(1) random access. So personally I can not think of any reason rather than just a minor overhead not to implement push_front/pop_front for <vector>. Any thoughts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We already have something as you describe in the STL. It is named deque.

As you wrote there IS actually some overhead. So if you need this functionality and you have no problem with the overhead, use deque. If you do not require it, you do not want the overhead, so it is better to have something that avoids this overhead, named vector.

And as an addition: vector guarantees that all its elements are stored in contiguous storage locations, so you can apply pointer arithmetic. This is not the case for a circular buffer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...