Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: mixture between vector and list: something like std::rope?

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:

  • It must reallocate if it doesn't fit anymore.
  • It doesn't really work for huge amounts of data (because you just cannot always get very big chunks of continuous free memory).

std::list is bad because:

  • It makes an allocation on every single push_back. That is slow and leads to a lot of memory fragmentation.

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?

like image 450
Albert Avatar asked Sep 22 '10 16:09

Albert


People also ask

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

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.

Is std::vector a 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).

Can a vector have multiple data types C++?

“No” C++ is a statically-typed language. A vector will hold an object of a single type, and only a single type.

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

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.


1 Answers

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.

like image 174
James McNellis Avatar answered Oct 03 '22 01:10

James McNellis