The difference between vector and deque [duplicate]

落花浮王杯 提交于 2020-07-17 02:21:09

问题


As vector and deque both provides a function to push_back the element at the last.

where deque also provides a function push_front to insert the element at the beginning, which is bit costly in case of vector.

My question is when we can achieve the same functionality (push_back) of vector by using deque, then why vector is required?


回答1:


One main difference between vectors and deques is that the latter allows efficient insertion at the front of the structure as well as the back.

Deques also do not guarantee that their elements are contiguous in memory so the at-style operator (indexing) may not be as efficient.

Note that the difference is unlikely to matter in practice for smaller collections but would generally become more important if, for example, the collection size increases or you're modifying it many times per second.




回答2:


Performance, mainly. An std::deque has all of the functionality of std::vector, at least for normal use, but indexing and iterating over it will typically be somewhat slower; the same may hold for appending at the end, if you've used reserve. And of course, std::vector is the default container, using anything else will suggest to the reader that you have special requirements.

std::vector also guarantees contiguity, so it (and only it) can be used to interface legacy functions which require a T* or a T const*.

I might add that the one time I actually had a performance issue, and measured, std::vector was faster than std::deque, despite the fact that I was regularly removing elements from the front (using the container as a queue, pushing at the back, and popping at the front). I don't know if that generalizes, however; in my case, the queue was relatively short (never more than about 15 elements, and usually many less), and the contents were char, which is extremely cheap to copy. But in general, I'd use std::vector even if I needed to remove elements from the front, if only because of its better locality. I'd probably only consider std::deque if I expected thousands of elements, which were expensive to copy.




回答3:


std::deque is a double-ended queue. It provides efficient insertion and deletion of elements at the beginning also, not just at the end, as std::vector does. Vectors are guaranteed to store the elements in a contiguous storage, therefore you can access its elements by index/offset. std::deque does not offer this guarantee.



来源:https://stackoverflow.com/questions/22068188/the-difference-between-vector-and-deque

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!