1

I'm a bit confused about how to properly use the Binary Heap provided in std.container. More specifically, I wanted to create a maximum heap of integers, so I tried writing

auto maxHeap = BinaryHeap!int();

and got a compiler complaint about int not being sliceable with []. I've tried to read the documentation for it on Phobos, but I don't understand how to create a new, empty binary heap designed to store integers.

Could someone please lend me a hand?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Koz Ross
  • 3,040
  • 2
  • 24
  • 44

2 Answers2

5

There is an interesting thread about BinaryHeaps.

As it's explained in the thread, you can try to use it this way:

import std.container: Array, heapify;

void main()
{
    int[] arr = [1, 2, 3];
    auto wrapped = Array!int(arr);
    auto queue = heapify(wrapped);
}
DejanLekic
  • 18,787
  • 4
  • 46
  • 77
Cedric Morent
  • 1,719
  • 1
  • 14
  • 25
1

Well, I humbly believe you would not be confused if you read documentation about BinaryHeap.

The first sentence clearly explains the crucial information:

Implements a binary heap container on top of a given random-access range type (usually T[]) or a random-access container type (usually Array!T).

Here is what you should do:

import std.stdio;
import std.container;

void main(string[] args) {
    int[] arr = [1, 4, 12, 19];
    auto bh = BinaryHeap!(int[])(arr);

    writeln(bh.length); // prints 4
}

It is worth of reminding people that D array is a random-access range.

DejanLekic
  • 18,787
  • 4
  • 46
  • 77