Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

So my question is

  • When exactly do you prefer std::list over std::vector? and why exactly?
  • When do you prefer std::vector over std::list? and why?

If there is performance consideration, then please list them too with detail explanation/information.

If possible, quote some references also, to support your answer.

like image 289
Nawaz Avatar asked Feb 20 '11 12:02

Nawaz


People also ask

In what cases is it preferred to use a list rather than a vector?

In general, use vector when you don't care what type of sequential container that you're using, but if you're doing many insertions or erasures to and from anywhere in the container other than the end, you're going to want to use list. Or if you need random access, then you're going to want vector, not list.

What is the difference between std::list and std::vector?

Hence std::list provides some extra functions for Sorting, Splicing, Removing elements and identifying unique elements. Vector provides the random access and hence can be used with STL algorithms that uses Random Access Iterators.

Is list better than vector?

std::vector is insanely faster than std::list to find an element. std::vector performs always faster than std::list with very small data. std::vector is always faster to push elements at the back than std::list. std::list handles very well large elements, especially for sorting or inserting in the front.

When would you use a list C++?

If you insert, remove, and move elements often in the middle of a container, consider using a list. Lists provide special member functions to move elements from one container to another in constant time.


1 Answers

So my question is: when exactly do you prefer std::list over std::vector?

When I need a sequential container in a performance-sensitive area and profiling shows std::list is faster.

So far, this has never happened to me.

(I might be tempted to try std::list first when I would have to store very big objects with lots of insertion/removal in the middle. However, in practice, I've never come across such a use-case.)

like image 111
sbi Avatar answered Oct 12 '22 00:10

sbi