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
std::list
over std::vector
? and why exactly? 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.
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.
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.
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.
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.
So my question is: when exactly do you prefer
std::list
overstd::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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With