Vector vs list according to Stroustrup [duplicate]

2019-02-06 06:23发布

问题:

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

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

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

Relative performance of std::vector vs. std::list vs. std::slist?

and

vector vs. list in STL

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?

回答1:

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.