質問

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?

役に立ちましたか?

解決

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);
}

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top