Not so far I've learned how std::deque
is implemented under the hood, and discovered that it's something like an array of pointers to n-byte arrays, where the data is actually stored. So now I have a couple of questions related to deques.
A picture that describes my current knowledge about it's structure:
The questions are:
When a
push_front
operation is being performed and there is no free space in Data Block 0, a new Data Block is allocated on heap and a pointer to this freshly allocated memory is inserted into 'Map' array like in ordinary array -- in O(number_of_blocks) time, yes?How to sort this beast? Can't imagine anything better then copy all the data into array, sort it, and then put it back. But this approach requires O(n) auxiliary memory... But!
std::sort
provides similar interface for sorting bothstd::vector
andstd::deque
. How are different algoritms for different data structures implemented? Using a template specialization? If so, whystd::list
can't be sorted usingstd::sort
? Or, maybe,std::sort
doesn't care about internal structure of this containers and just uses iterators and methods, that are similar in bothstd::vector
andstd::deque
(likeoperator[]
,size()
, etc)? This idea sounds reasonable and an answer to "why can'tstd::sort
sortstd::list
?" becomes evident.How are the sizes of data blocks being chosen? You'll say "It's implementation dependent", but please tell more about different implementations and motivation behind solutions.
Need clarifications here. Thanks.
To answer to your first question, yes, that's pretty much how it works. One can note that this approach can be extended into a multi-level hierarchical structure. But practical implementations usually stick to two-level structure, exactly as shown in your picture.
For your second question, if you are taking about
std::sort
, thenstd::sort
works without any knowledge about the mechanics of the actual container. If works on a range of random-access iterators. Sincestd::deque
's iterators are random-access iterators,std::sort
can be applied tostd::deque
. And one can actually argue that random access to elements of such data structure is rather efficient. It is not as efficient as random access in a vector, but it is still pretty efficient to make sense in the context ofstd::sort
.You cannot use
std::sort
withstd::list
becausestd::list
's iterators are not random access iterators. If you wish, you can implement your own trivial (slow) version of random-access iterator forstd::list
. You will be able to applystd::sort
to a range of such iterators and thus sort anstd::list
withstd::sort
. But for obvious reasons it will be prohibitively inefficient.In case of
std::deque
random access iterators are more than adequately efficient.I'm not prepared to answer the third question. In fact I wouldn't be surprised to find out that these sizes are chosen empirically, based on a bunch of experiments. And, of course, there's probably no "one size fits all" solution.