您的位置:首页 > 产品设计 > UI/UE

STL中为什么我们更偏爱vector而不是deque

2016-04-21 00:24 696 查看
重读经典《STL源码剖析》

想到了一个问题?

为什么我或是我们更偏爱vector,而冷落deque呢?

至少对于我来说deque只是存在教科书中,或是面试官的口中。



这里就对两种STL容器进行简单的比较。

首先需要明确:

二者都是线性连续的存储空间。

vector是如何自动增加内存空间的?

我们知道,我们之所以爱vector,就是它可以自动增加内存。但是实际上不是我们想象的那样高效的:比如现在vector有四个元素,占内存为4。当我们插入第五个元素的时候,并不是内存变为5,而是重新开辟了更大的内存,比如大小为8。然后将原来内存中的4个元素和新插入的元素拷贝到新开辟的内存中,然后释放原来的内存。

deque是如何实现从前插入和删除的?

这里要明确一点,虽说deque是连续的存储空间,但是这个连续是我们看上去的表面上的连续。deque不会像是vector那样重新开辟更大的空间,然后拷贝。deque是分段连续空间。

deque是如何实现分段连续空间的?

采用了一块所谓的map作为主控,这里我提到的map不是STL中的map。

deque与vector比增加了什么?

双端队列,当然增加的是在头的操作:

push_front() - Adds elements to the front of a deque.

pop_front() - Removes elements from the front of a deque.

deque与vector比失去了什么?

capacity() - Returns the current capacity of a vector.

reserve() - Allocates room for a specified number of elements in a vector.

为什么deque没有capacity和reserve方法?

The deque allocates memory in chunks as it grows, with room for a fixed number of elements in each one. However, vector allocates its memory in contiguous blocks (which isn’t necessarily a bad thing). But the interesting thing about vector is that the size of the internal buffer grows increasingly larger with each allocation after the vector realizes the current one isn’t big enough. The following experiment sets out to prove why deque doesn’t need capacity() or reserve() for that very reason.

如何选用deque和vector?

c++标准中怎么说:

vector is the type of sequence that should be used by default. … deque is the data structure of choice when most insertions and deletions take place at the beginning or at the end of the sequence.

When to choose deque over vector:

One should choose deque over vector if he wants to either add or delete from both the ends like implementing a Queue.

When to choose vector over deque:

One should choose vector if insertion or deletions are required mostly in end like implementing a Stack.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: