Why after writeln the binaryHeap become empty?
Johannes Loher
johannes.loher at fg4f.de
Tue Jun 18 17:25:51 UTC 2019
Am 18.06.19 um 17:45 schrieb lili:
> Hi Guys:
> see this code
> ~~~
> int[] ar = [1,2,3,4,52,34,22];
> auto h = heapify(ar);
> assert(h.length() == ar.length);
> writeln("h:",h);
> assert(h.empty());
> ~~~
> dmd v2.086.0 run all assert passed. Why?
The result of heapify is a BinaryHeap, which is a range. writeln
basically prints ranges by iterating over them and printing each element
(except for the types which are special cased, such as dynamic arrays
etc.). However, ranges are consumed by iterating over them, which
explains the behavior because writeln is not special cased for BinaryHeaps.
In order to avoid this, you can make a copy of the BinaryHeap before
printing it:
```
import std;
void main()
{
int[] ar = [1, 2, 3, 4, 52, 34, 22];
auto h = heapify(ar);
assert(h.length() == ar.length);
writeln("h:", h.dup);
assert(!h.empty());
}
```
Funnily enough, BinaryHeap does not implement a "save" method, which is
the usual way of making ranges copiable, i.e. making them ForwardRanges.
In this case I believe save could even simply be an alias to dup.
More information about the Digitalmars-d-learn
mailing list