Min-Heap and Hash Table help

Chris Cain clcain at uncg.edu
Tue Apr 3 14:24:22 PDT 2012


On Tuesday, 3 April 2012 at 19:38:12 UTC, Chris Pons wrote:
> Thanks, yes, that did work. However now when trying to insert 
> nodes I get this error: Cannot grow a heap created over a 
> range. I This is what I have: ...

Hey there,

BinaryHeap is using the "slice of memory" you're giving it to use 
as a heap. In the first code you gave, your array is length = 0. 
In other words, there is no place to actually insert things!

When you specified Node[2500] a, you are making an array of size 
2500 filled with zeros. You still don't have any room to insert, 
because all of the space in the array is still taken up.

Depending on your data, your option might be to just insert all 
the items you want first, then heapify the resulting array, maybe 
like this:
Node[] a;
foreach(i; 0..5) {
	Node nextNode;
	nextNode.fScore = (i*3) % 5;
	a ~= nextNode;
}
auto b = BinaryHeap!(Node[], "a.fScore > b.fScore")(a);

while(!b.empty()) {
	writeln(b.front());
	b.removeFront();
}

Otherwise, if you know a maximum bound for the number of inputs, 
you could simply allocate enough memory to store your items, and 
then use the initialSize parameter.
Something like this:
Node[] a;
// or Node[10] a; for a static array sized to 10...
a.length = 10;
// 0 states that nothing is in the heap
auto b = BinaryHeap!(Node[], "a.fScore > b.fScore")(a, 0);
foreach(i; 0..5) {
	Node nextNode;
	nextNode.fScore = (i*3) % 5;
	b.insert(nextNode);
}
while(!b.empty()) {
	writeln(b.front());
	b.removeFront();
}

The thing you looked like you were doing with your third option 
looks like it was getting close to the right track for yet 
another potential solution, but apparently a bug prevents this 
from working: http://d.puremagic.com/issues/show_bug.cgi?id=6959
If this was working, then you could use Array for an unbounded 
input (because it supports insertBack).

I hope this helps!



More information about the Digitalmars-d-learn mailing list