www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - BinaryHeap usage

reply Matthias Walter <xammy xammy.homelinux.net> writes:
Hi all,

suppose I have an array of comparable Foo structs which I want to access
in a sorted order (e.g. a priority queue) using a BinaryHeap object (I
know that for just sorting, the BinHeap is not the right tools), but I
do not want to change the order of the objects in the original array.

I have two ideas on how to do this and just want to know whether they
are the right way:

a) Have an array of Foo*, initialize it from the original and
instantiate the BinaryHeap with a Comparision-predicate that
dereferences first.

b) Have an array of indices that are indicies in the original array
(like a permutation in a permutation group) and access the corresponding
index of the original array for comparison.

Any further ideas for this problem, or did I cover everything already?

Matthias
Dec 14 2010
parent bearophile <bearophileHUGS lycos.com> writes:
Matthias Walter:

 Any further ideas for this problem, or did I cover everything already?

For a C programmer the solution with pointers seems more natural, for a Pascal-family programmer the solution with indexes seems more natural, a bit safer (and it is probably just as fast). A third possible solution is to turn Foo into a class, that in D are always managed by reference, so it moves just the references. Turning the Foos into Rebindable!Foo too may be used for your purpose. Bye, bearophile
Dec 14 2010