根据Stroustrup的向量vs列表 [英] Vector vs list according to Stroustrup

查看:78
本文介绍了根据Stroustrup的向量vs列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
何时更喜欢使用std :: list< T>而不是std :: vector< T> ;?

Possible Duplicate:
When do you prefer using std::list<T> instead of std::vector<T>?

我刚刚看过Bjarne Stroustrup录制的GoingNative'12谈话.而且我有点困惑.

I just watched the recording of the GoingNative'12 talk by Bjarne Stroustrup. And I'm a bit confused.

在本次演讲中,他特别讨论了vectorlist的问题,并建议在很多情况下,即使您密集地从中间插入/从中间插入和删除,vector还是更快,因为编译器可以优化很多东西,像紧凑的结构.结论(据我所知)是:首先使用vector,然后再考虑是否需要其他东西.这听起来很合理,但考虑到第一个观察结果,我应该考虑哪些标准?我一直认为,如果您频繁插入/删除-请使用列表.在此处的某些主题中建议了类似的内容.见

In this talk he in particular discusses the vector vs list question and suggest that in many cases vector is faster even if you insert and remove intensively to/from the middle, as compilers can optimize a lot of things and like compact structures. And the conclusion(as I understand it) is: first use vector and later think whether you need something else. That sounds reasonable, but taking into account the first observation, what criteria I should take into account? I always thought that if you insert/remove intensively - use list. Similar things are suggested in some topics here. See

std :: vector与std :: list的相对性能与std :: slist?

STL中的向量与列表

现在根据Stroustrup,我错了.

And now according to Stroustrup I was wrong.

我当然可以编写一些测试,并尝试弄清楚在每种特定情况下使用什么,但是有理论上的方法吗?

Of course I can write a couple of tests and try to figure out what to use in each particular situation, but is there a theoretical way?

推荐答案

std::vector相比,首选std::list的最重要动机是迭代器的有效性,而不是不是性能.如果在插入或擦除时,容器中还有其他迭代器,则可能需要std::list,因为插入不会使任何迭代器无效,而擦除操作只会使要擦除的元素的迭代器无效. std::list在性能上唯一获胜的时间是复制和分配非常昂贵,在这种情况下,修改包含的类以降低复制和分配的成本通常是一个更好的选择,而不是切换到.

The most important motivation for preferring std::list over std::vector is the validity of iterators, not performance. If at the time you're inserting or erasing, you have other iterators into the container, then you probably need std::list, since it insertion doesn't invalidate any iterators, and erasure only invalidates iterators to the element being erased. About the only time std::list will win on performance is when copy and assignment are extremely expensive, and in such cases, it's often a better choice to modify the contained class to reduce the cost of copy and assignment, rather than switching to std::list.

这篇关于根据Stroustrup的向量vs列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆