Whats wrong with binery heap or i am not understand something?

WebFreak001 d.forum at webfreak.org
Thu Apr 2 13:25:11 UTC 2020


On Thursday, 2 April 2020 at 12:59:06 UTC, AlexM wrote:
> Please explain me whats wrong with binery heap?!!!
>
> Simple example:
>
> import std.container.binaryheap;
> import std.stdio;
>
> void main()
> {
>     int[] a = [ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ];
>     int[] b = new int[a.length];
>     auto h = BinaryHeap!(int[], "a > b")(b, 0);
>     foreach (e; a)
>     {
>         h.insert(e);
>     }
>     writeln(b); // [1, 2, 3, 4, 7, 9, 10, 14, 8, 16]
>     writeln(h); // [1, 2, 3, 4, 7, 8, 9, 10, 14, 16]
>     writeln(h.length); // 0 ???????
>     h.insert(21);
>     writeln(h); // [21] ????????
>     writeln(h.length); // 0 ???????
> }

by iterating over it (writeln doing it) you are taking out all 
elements from the binary heap. You will either need to .dup it 
(will cause memory allocation, will only make a single additional 
copy) or convert it to an array using .array (will cause memory 
allocation, you can use it multiple times but not use it as 
binary heap anymore)

If BinaryHeap implemented a save() method it would be possible to 
do this without duplicating because writeln would call save to 
not modify the existing data.

If you only want to get the length and do something with the data 
exactly once, you can call .length before using the data to get 
the length of the data. If you get length after iterating over 
your data, your data will be gone at this point.

Otherwise you might want to try some containers library from dub 
for more advanced containers.


More information about the Digitalmars-d-learn mailing list