Q: How to create a class that accepts a comparator (for Max Heap and Min Heap)? 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!

A: Do as the standard library does and make the comparator a template argument:
template <typename T, typename SWOComp = std::less<T>>
class MyHeap
{
    SWOComp compare;
public:
    explicit MyHeap(SWOComp c = SWOComp()) : compare(c) { }
    // ...
};

Then, when you need to compare two elements a and b, use compare(a, b).
To instantiate an ordinary, <-ordered type, say something MyHeap<int>. To use the reverse ordering, say MyHeap<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.
