Creating a growable binary heap or priority queue using Phobos?

qznc qznc at web.de
Sat Jun 22 01:07:17 PDT 2013


On Saturday, 22 June 2013 at 07:48:25 UTC, qznc wrote:
> On Monday, 14 November 2011 at 06:15:18 UTC, SimonM wrote:
>> On 2011/11/14 02:10 AM, bearophile wrote:
>>> SimonM:
>>>
>>>> 2009, 27 April:
>>>> http://www.digitalmars.com/d/archives/digitalmars/D/std.algorithm.BinaryHeap_88811.html
>>>
>>> See the working version:
>>> http://rosettacode.org/wiki/Huffman_coding#D
>>>
>>> Bye,
>>> bearophile
>>
>> Okay, I looked at the example, and it seems that the only 
>> reason it works is because that piece of code never requires 
>> the array's length to grow larger than it's initial length (at 
>> the start of the loop, 2 elements are taken out, and at the 
>> end, only one is inserted back in).
>>
>> If I try using a BinaryHeap with a range, then, like the 
>> documentation mentions, I can't grow that BinaryHeap any 
>> larger than it's initial size, because I got the following 
>> error: "Cannot grow a heap created over a range". But somehow 
>> I can't get it working with an Array!(T) like the 
>> documentation implies it should be capable of?
>
> Is this problem resolved? I cannot produce a growable 
> BinaryHeap myself.

Ok, got it. Instead of using a dynamic array directly, wrapping 
it into a std.container.Array works.

import std.container: Array, heapify;

Foo[] arr = ...;
auto wrapped = Array!Foo(arr);
auto queue = heapify(wrapped);

In general, other containers should work as well, since 
containers provide an insertBack method whereas the builtin 
arrays/ranges do not.


More information about the Digitalmars-d-learn mailing list