When storing a bunch of items and I don't need random access to the container, I am using an std::list
which is mostly fine. However, sometimes (esp. when I just push back entries to the back and never delete somewhere in the middle), I wish I had some structure with better performance for adding entries.
std::vector
is bad because:
std::list
is bad because:
So, something in between is what I want.
Basically, I want something like std::list< boost::array<T, 100> >
or so. Or maybe instead of 100
, let it be 4096/sizeof(T)
. Maybe also std::list< std::vector<T> >
and the first vectors can be small and then further ones can grow. Actually I want to have that hidden from the usage, so I can just do a mycontainer.push_back(x)
.
std::rope
is a bit similar to that but it is not available in the standard.
Is there something like this in Boost or so?
List does not have default size. In vector, each element only requires the space for itself only. In list, each element requires extra space for the node which holds the element, including pointers to the next and previous elements in the list.
In this article, when I talk about a list it is the std::list implementation and vector refers to the std::vector implementation. It is generally said that a list should be used when random insert and remove will be performed (performed in O(1) versus O(n) for a vector).
“No” C++ is a statically-typed language. A vector will hold an object of a single type, and only a single type.
Difference between std::vector and std::array in C++ As array is fixed size, once initialized can't be resized. Vector occupies more memory. Array is memory efficient data structure. Vector takes more time in accessing elements.
Have you considered using std::deque
? Its elements are not stored contiguously but it does allow random access to elements; if you are only inserting elements at the beginning or end of the sequence, it may give better performance than a std::vector
.
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