Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector implemented with many blocks and no resize copy

I'm wondering if it would be possible to implement an stl-like vector where the storage is done in blocks, and rather than allocate a larger block and copy from the original block, you could keep different blocks in different places, and overload the operator[] and the iterator's operator++ so that the user of the vector wasn't aware that the blocks weren't contiguous.

This could save a copy when moving beyond the existing capacity.

like image 896
larboyer Avatar asked Feb 07 '12 21:02

larboyer


1 Answers

You would be looking for std::deque

See GotW #54 Using Vector and Deque

In Most Cases, Prefer Using deque (Controversial)

Contains benchmarks to demonstrate the behaviours

The latest C++11 standard says:

§ 23.2.3 Sequence containers

[2] The sequence containers offer the programmer different complexity trade-offs and should be used accordingly. vector or array is the type of sequence container that should be used by default. list or forward_list should be used when there are frequent insertions and deletions from the middle of the sequence. deque is the data structure of choice when most insertions and deletions take place at the beginning or at the end of the sequence.

FAQ > Prelude's Corner > Vector or Deque? (intermediate) Says:

  • A vector can only add items to the end efficiently, any attempt to insert an item in the middle of the vector or at the beginning can be and often is very inefficient. A deque can insert items at both the beginning and then end in constant time, O(1), which is very good. Insertions in the middle are still inefficient, but if such functionality is needed a list should be used. A deque's method for inserting at the front is push_front(), the insert() method can also be used, but push_front is more clear.

  • Just like insertions, erasures at the front of a vector are inefficient, but a deque offers constant time erasure from the front as well.

  • A deque uses memory more effectively. Consider memory fragmentation, a vector requires N consecutive blocks of memory to hold its items where N is the number of items and a block is the size of a single item. This can be a problem if the vector needs 5 or 10 megabytes of memory, but the available memory is fragmented to the point where there are not 5 or 10 megabytes of consecutive memory. A deque does not have this problem, if there isn't enough consecutive memory, the deque will use a series of smaller blocks.

[...]

like image 99
sehe Avatar answered Sep 24 '22 15:09

sehe