In order to learn more about Heaps, I implemented my own MaxHeap class. I have tested it and it is working fine. Now, I want to create a MinHeap. The only thing that is going to be different across the two (MaxHeap and MinHeap) is just the comparisons (i.e. changing < to >=). So how can I redesign my class to work both ways? What comes to my mind, is passing of a comparison function while creating the objects. Is that the best way? If so, how do I go about doing it? I don’t even know the right keywords to search for what I am looking. Please explain the design of such a class and point me to some tutorials. Thanks!
Share
Do as the standard library does and make the comparator a template argument:
Then, when you need to compare two elements
aandb, usecompare(a, b).To instantiate an ordinary,
<-ordered type, say somethingMyHeap<int>. To use the reverse ordering, sayMyHeap<double, std::greater<double>>. Etc etc.Don’t worry about the extra member object; with empty-base-class optimizations this won’t cost you anything for stateless comparators.