你什么时候更喜欢使用 std::list<T>而不是 std::vector<T>?
我自己从未使用过 std::list
.我想知道当我们已经有了 std::vector<T>
这就像具有连续内存的数组时,人们什么时候使用它.当我们需要顺序容器时,std::vector
似乎是一个完美的选择!
I've never used std::list<T>
myself. I was wondering when people use it when we already have std::vector<T>
which is just like arrays with contiguous memory. std::vector
seems like a perfect choice when we need sequential container!
所以我的问题是
- 你究竟什么时候更喜欢
std::list
而不是std::vector
?为什么? - 你什么时候更喜欢
std::vector
而不是std::list
?为什么?
- When exactly do you prefer
std::list
overstd::vector
? and why exactly? - When do you prefer
std::vector
overstd::list
? and why?
如果有性能方面的考虑,也请列出它们并附上详细说明/信息.
If there is performance consideration, then please list them too with detail explanation/information.
如果可能,还引用一些参考资料,以支持您的回答.
推荐答案
列表更适合在中间的任何位置插入或删除,向量更适合在末尾插入.
Lists are better for inserting or deleting anywhere in the middle, vectors are better for inserting at the end.
向量也更适合访问元素.
Vectors are also better for accessing elements.
这是他们实施方式的产物.
This is an artefact of the way they're implemented.
因此,如果集合变化很小(与访问相比)或变化集中在最后,我会使用向量.
So, if a collection changes very little (compared to accesses) or the changes are concentrated at the end, I'd use a vector.
如果更改的数量很大(与访问相比)并且它们不在最后,我会使用列表.
If the number of changes is substantial (compared to accesses) and they're not at the ends, I'd use a list.
举例来说,在程序启动时读入一个集合并且几乎从不改变它(或者如果改变只是添加到最后),这将是一个很好的向量候选.
By way of example, reading in a collection at program start-up and hardly ever changing it (or if the changes are only adding to the end), this would be a good candidate for a vector.
另一方面,对于一个特别受欢迎和善变的摇滚明星的电话簿应用程序,我会寻找一个列表.实际上,我希望建立数据库连接,但这是我能在短时间内提出的最佳示例:-)
On the other hand, a phone book application for a particularly popular and fickle rock star, I'd be looking towards a list. Actually I'd be looking toward a database connection but that was the best example I could come up with at short notice :-)
至于参考文献,最新的 C++0x 草案(在此回答时)在部分(23.3.4,列表)中说明:
As to references, the latest C++0x draft (at the time of this answer) states in part (23.3.4, lists):
列表是一个序列容器,它支持双向迭代器并允许在序列内的任何地方进行恒定时间插入和擦除操作,并自动处理存储管理.与向量和双端队列不同,不支持对列表元素的快速随机访问.
A list is a sequence container that supports bidirectional iterators and allows constant time insert and erase operations anywhere within the sequence, with storage management handled automatically. Unlike vectors and deques, fast random access to list elements is not supported.
第 23.3.5 节(关于向量):
Section 23.3.5 (on vectors):
向量是一个支持随机访问迭代器的序列容器.此外,它支持(摊销)最后的恒定时间插入和擦除操作;中间插入和擦除需要线性时间.
A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time.
相关文章